javascript - Backbone.js popover implementation -
i new backbone.js , first project implement popover view can reused throughout project easily. defined following requirements.
requirements
the popover should referenced element in dom able calculate popover's position , open/close popover. reference acts popover toggle button
a new popover appended body, on close popover destroyed , removed dom
any click outside of popover forces popover close , destroyed
the popover backbone view , should independent it's parent/creator view, communication open/close should performed using events
popovers content may view
the implementation:
first create view popover reference:
my.views.toggle = backbone.view.extend({ tagname: 'a', events: { 'click': 'toggle' }, serialize: function() { return { model: this.model }; }, initialize: function() { this.listento(this.model, 'change', this.render); }, afterrender: function() { //here should add popover, right? }, toggle: function(){ app.vent.trigger('my:navbar:toggle'); } });
in above implementation respect requirement #4. have think #1. able give papover reference of parent view, have wait until parent has finished rendering right? have create popover inside afterrender function:
var popover = new popover.views.default({ content: "hey there, popover", reference: this.$el });
the problem violates requirement #2. because afterrender function called twice, before , after model has changed. , whenever model changes again, function called too. there many instances of popover in dom.
my question is, how can guarantee there 1 popover instance in dom?
my.views.popover = backbone.view.extend({ classname: 'popover', initialize: function(options) { this.visible = false; this.content = options.content; this.reference = options.reference; app.vent.on('member:navbar:toggle', this.toggle, this); this.render(); }, afterrender: function() { $('body').append(this.$el.append(this.content)); }, show: function() { this.visible = true; this.$el.show(); }, hide: function() { this.visible = false; this.$el.hide(); }, toggle: function() { this.visible ? this.hide() : this.show(); } });
looks this, many underlaying popovers:
i'll quite opinionated question,
first, there should main view handling body, i.e. appview({el:'body'})
, view should boostrap application , render views go inside it.
secondly,
afterrender: function() { $('body').append(this.$el.append(this.content)); },
i think view should responsible created for. manage it, view should 1 positioning , managing of it, except main view containing body of course,
my.views.appview = backbone.view.extend({ el: 'body', initialize : function(){ this.popup = new popover(...); }, render : function(){ this.titlebar.render()... this.content.render()... ... this.popup.render().appendto(this.$el)...; } });
i think gives me clear structure of views , responsibilities.
Comments
Post a Comment