2014-05-06 140 views
0

嘗試在模型上設置成功的綁定。骨幹模型綁定

綁定在向模型添加/刪除/更新值時起作用。但一旦我重新創建模型,綁定停止工作。我需要創建新模型,以便在保存到Collection時獲取新的id/cid。

我試過this.model.clear(),但是沒有爲模型分配新的id/cid。

希望它是有道理的。謝謝!

app.View = Backbone.View.extend({  

    initialize: function() { 
     this.model = new app.Model(); 
     this.listenTo(this.model,'change', this.semaphore); 
    }, 

    start: function(value) { 
     // Create new model unless running app first time 
     if(this.model.attributes.title != null) this.model = new app.Model(); 
     this.model.set({title: value}); 
    }, 

    semaphore: function() { 
     // Doesn't get call when new model gets reassigned 
     // Do stuff... 
    } 
} 
+1

爲什麼不將你的所有綁定調用一個單獨的方法?然後從'initialize'調用該方法,並在分配新模型時再次調用該方法。這種「其他方法」大概也會處理來自舊模型的解綁器,以幫助防止內存泄漏等。 –

+0

這是一個想法。你可以給我一個例子嗎? 因爲在重新分配和重新綁定之前應該發生解除綁定.. 謝謝! – Oriol

回答

0

沒有什麼幻想,但它的工作原理:

initialize: function() { 
    // Leave it blank 
}, 

// New element gets created within the view 
start: function(value) { 
    // Creates new model 
    this.model = new app.Word(); 
    // Binds it to a function 
    this.listenTo(this.model,'change', this.semaphore); 
    // Set value(s) so binding function reacts to it  
    this.model.set({title: value}); 
},