2012-06-18 48 views
0

假設我有一個模型和一個視圖,該視圖有兩個方法:一個是綁定文檔mousemove事件,另一個是解除綁定方法,defalut我給文檔mousemove事件,一旦模型enable值改變,我會調用該視圖的解除綁定方法:Backbone.js:「超出最大調用堆棧大小」錯誤

window.ConfigModel = Backbone.Model.extend({ 
     defaults: { 
      'enable':0 
     }, 
     initialize: function(){ 
      this.bind("change:enable", function() { 
       var portView2 = new PortView(); 
       portView2.viewOff();       
      }); 
     }, 
     change:function() { 
      this.set('enable', 9); 
     } 
    }) 

    window.PortView = Backbone.View.extend({ 
     viewOn: function() { 
      $(document).on('mousemove', function() { 
       console.log('move') 
      }) 
     }, 
     viewOff: function() { 
      $(document).off('mousemove'); 
     } 
    }) 

然後我把一個input對文檔調用模式改變:

$('input').click(function() { 
     var configModel = new ConfigModel(); 
     configModel.change(); 
    }) 

啓動腳本是:

var portView1 = new PortView(); 
portView1.viewOn(); 

的問題是,一旦我稱之爲點擊輸入按鈕,鍍鉻會告訴我一個錯誤:Maximum call stack size exceeded似乎change被調用許多times.So什麼是我的問題,這個問題,我怎麼能解決這個問題

回答

1

骨幹機型已經有了change method

changemodel.change()

Manually trigger the "change" event and a "change:attribute" event for each attribute that has changed. If you've been passing {silent: true} to the set function in order to aggregate rapid changes to a model, you'll want to call model.change() when you're all finished.

想必內部骨幹東西試圖調用configModel.change()並讓你的change版本觸發B的內部另一change()通話ackbone運行你的change ...,直到堆棧炸燬。

您應該爲您的change方法使用不同的名稱。


這就是說,你的代碼結構有點奇怪。模型聽取了他們對自身的活動都很好,但模型創建一個視圖是奇數:

initialize: function() { 
    this.bind("change:enable", function() { 
     var portView2 = new PortView(); 
     portView2.viewOff();       
    }); 
} 

和實例化一個視圖僅僅是調用一個方法,然後把它扔掉是奇怪的是創建新模型只是爲了觸發一個事件。

我想你可能想要一個ConfigModel實例作爲你的應用程序狀態的一部分,比如app.config。然後你click處理程序會跟這個模型:

$('input').click(function() { 
    app.config.enable_level_9(); // or whatever your 'change' gets renamed to 
}); 

然後,你有你的應用程序的其它部分(不一定是視圖),對於改變監聽app.config並進行適當的操作:

app.viewOn = function() { 
    $(document).on('mousemove', function() { 
     console.log('move') 
    }); 
}; 
app.viewOff = function() { 
    $(document).off('mousemove'); 
}; 
app.init = function() { 
    app.config = new ConfigModel(); 
    app.viewOn(); 
    $('input').click(function() { 
     app.config.enable_level_9(); 
    }); 
    // ... 
}; 

,然後用單app.init()調用啓動應用程序:

$(function() { 
    app.init(); 
}); 
+0

我必須改變方法名,第一個問題有茶但另一個問題是:viewOff方法不起作用,它不能解除綁定文檔的mousemove事件,我該如何解決這個問題?使用console.log我可以看到該方法已被調用,但不能解除綁定 – hh54188

+0

@ hh54188:重命名'更改'工作正常:http://jsfiddle.net/ambiguous/b7rUT/你仍然有一個奇怪的應用程序結構,但它的工作原理。 –

相關問題