0

我想創建一個單身人士對象作爲骨幹視圖的模型,並且我希望在這個單身人士對象被更改和更新時重新呈現視圖。我不知道下面的代碼會做的正確的方式或不單身人士對象上的骨幹事件監聽器

型號

define(function(require) { 
    var Singleton = require("modules/Singleton"); 
    var Singleton = null; 
    var SingletonHolder = { 

     init: function() { 
      Singleton = new Singleton(); 
      return Singleton.fetch(); 
     }, 

     current: function() { 
      return Singleton; 
     }, 

     refresh: function() { 
      return Singleton.fetch(); 
     } 
    }; 

    return SingletonHolder; 
}); 

控制器

var currentObj = SingletonHolder.current(); 
var tempView = new TempView({ 
      model: currentObj 
}); 

查看

var TempView = Backbone.View.extend({ 
    initialize: function() { 
     this.listenTo(this.model, "change", this.render); 
    } 

    render: function() { 
     ... 
    } 

}); 

由於某些原因,它不起作用。我錯過了什麼嗎?我還嘗試調用Singleton.refresh,它將它發送到服務器端並從數據庫中獲取最新數據,但它不檢測更改並重新呈現視圖。

回答

1

如果您已經使用requirejs,則不必定義Singleton。

辛格爾頓:

define(['models/foo'], function(FooModel){ 
    return new FooModel; 
}) 

控制器:

define(['foosingleton', 'tempview'], function(fooSingleton, TempView){ 
    var tempView = new TempView({ 
    model: fooSingleton 
    }); 
}); 

這裏是一個類似的問題:Is it a bad practice to use the requireJS module as a singleton?