我需要做这样的事情:
new app.view().done(function() {})
那是因为我在initialize函数中异步设置了view元素,我需要在实例化后立即使用该元素。
如果我这样做它不起作用:
var view = new app.view();
var $el = view.$el;
因为视图元素还没有准备好。
同样,我需要这样的事情:
new app.view().done(function(view) {
var $el = view.$el;
})
但我找不到任何方法可以做到这一点。覆盖构造函数会帮助我吗?
答案 0 :(得分:1)
您可以在$el
异步创建后触发事件:
app.view = Backbone.view.extend({
initialize: function ()
{
// async setup the $el and then do the following after it is created
this.trigger('el:created', this.$el);
}
});
然后所有其他观点都可以听取此事件并采取相应行动:
app.anotherView = Backbone.view.extend({
initialize: function ()
{
var otherView = new app.view();
// Only fires once so only listen once
this.listenToOnce(otherView, 'el:created', this.createEl);
},
createEl: function ($el)
{
//do something with $el here
}
});
app.view = Backbone.view.extend({
initialize: function ()
{
this.elCreation = $.Deferred();
// async setup the $el and then do the following after it is created
this.elCreation.resolve(this.$el);
}
});
new app.view().elCreation.done(function($el)
{
//do something with $el here
});