2013-04-15 77 views
0

我在骨幹js中創建我的「Hello world」應用程序。我被困在最基本的東西。無法訪問屬性模型骨幹js

var gs = { documentRoot:「」 }; //爲我們的應用程序創建命名空間

gs.Test = Backbone.Model.extend({ 
    url: gs.documentRoot+'/test.php', 
    initialize: function(){ 
     this.fetch(); 
    } 
}); 

gs.TestView = Backbone.View.extend({ 
    render: function(){ 
        console.log(this.model); 
     console.log(this.model.get('testId')); 
    } 
}); 

var testM = new gs.Test(); 

var test = new gs.TestView({model: testM}); 
test.render(); 

在這裏,當我在控制檯登錄模式,它顯示了從服務器獲取屬性,但我無法從test.get(「屬性」)訪問這些屬性。我試着記錄test.attributes,它給出了空對象,但是當我登錄測試時,它顯示屬性對象中的那些屬性。

回答

1

fetch是異步方法,所以你必須等待一段時間。 在這種情況下,最好的解決辦法是承諾:

test.fetch().done(function() { 
    console.log(test); 
}); 

你更新的模型:

initialize: function() { 
    // save link to promise 
    this.deferred = this.fetch(); 
} 

而且你的渲染功能:

render: function() { 
    // use promise to render view after model will be fetched 
    // use `bind` to save context of this view 
    this.model.deferred.done(_.bind(function() { 
    // model is fetched 
    // all operations goes here 
    console.log(this.model.get('testId')); // <- proper value 
    }, this)); 
    console.log(this.model.get('testId')); // <- undefined 
} 

更多關於AJAX你可以在這裏閱讀http://api.jquery.com/jQuery.ajax

var TestModel = Backbone.Model.extend({ 
    url : '/test.php' 
}); 

var test = new TestModel(); 

// `context` context to be passed to any callback function 
test.fetch({context:test}).done(function() { 
    // `this` is equals to `test` (`context` option) 

    // In case if you want to get all model data: 
    // the best way to get model data for read-only mode. 
    // this metod return a copy of the model's attributes 
    console.log(this.toJSON()); 
    // you can also use `this.attributes` but this is not recommended 
    console.log(this.attributes());  

    // In case if you want to get some model data: 
    console.log(this.get('some_attribute')); 
    // If you want to get `c` from this model ({a:{b:{c:1}}}): 
    console.log(this.get('a').b.c);  
}); 
+0

我沒有看到任何人爲簡單的骨幹js應用程序實現承諾。應該有一個簡單的方法來做到這一點?這只是開始,所以你可以告訴我在應用程序的更遠的地方,我可以訪問這些屬性。我沒有寫視圖代碼,但我也無法訪問它的屬性。 –

+0

骨幹使用jQuery ajax http://api.jquery.com/jQuery.ajax我要用示例更新我的答案 –

+0

請參閱更新後的問題。 –

2

model#fetch方法的優點是可以傳遞給取一個successerror回撥選項。當來自服務器的響應已經到來時,成功回調被調用。

測試模型的屬性獲取正確的方法是

test.fetch({ 
    success: function(model){ 
     // model here and test are same 
     console.log(model); 
     console.log(test.toJSON()); 
     // access your attribute with name `attributeName` 
     console.log(test.get('attributeName')); 
    } 
}); 
1

對於那些被卡住了同樣的問題誰,這裏是從圖書館自身的解決方案。

使用模型的內置'sync'事件獲取fetch()/save()調用後的模型屬性。

testM.on('sync',function(){ 
    test.render(); 
});