rea*_*lph 10 javascript model coffeescript backbone.js parse-platform
我对Backbone相当新,并且想知道如何从将模型注入依赖关系的视图中访问模型的数据和函数.
我的模型看起来像这样:
countries.coffee
define [
'underscore'
'backbone'
'parse'
], (_, Backbone, Parse) ->
'use strict';
class CountriesModel extends Parse.Object
countries: ['GB','US','FR','JP','WL','ZM','NG']
returnCode = (code) ->
return code
Run Code Online (Sandbox Code Playgroud)
我的观点看起来像这样:
country.coffee
define [
'jquery'
'underscore'
'backbone'
'templates'
'models/projects'
'models/countries'
], ($, _, Backbone, JST, CountriesModel, ProjectModel) ->
class CountryView extends Backbone.View
...
console.log countries
returnCode(4)
Run Code Online (Sandbox Code Playgroud)
我正在注入CountriesModel作为依赖项,但是当我调用该函数或记录时,countries我收到以下错误:
Uncaught ReferenceError: returnCode is not defined
Run Code Online (Sandbox Code Playgroud)
我无法弄清楚我做错了什么.任何帮助表示赞赏.提前致谢!
UPDATE
我已经更新了上面的代码以提供更多的上下文.
我正在尝试创建一个可重用的模型(CountriesModel),因此我可以在我的应用程序中访问该countries数组和returnCode不同视图上的函数.但我无法弄清楚如何在我的网站上访问它们CountryView.
我CountryView已经需要一个模型了ProjectModel,我可以ProjectModel像这样调用函数和数组:
this.model.exampleArray
this.model.exampleFunction()
我无法弄清楚我是如何调用函数或数组的CountriesModel.
谁知道我做错了什么?
说实话,我真的不明白你为什么使用你的模型作为部门。一个好的视图应该从模型中抽象出来,并且模型应该附加到路线的视图上。
// this goes in your view file
var CountryView = Backbone.view.extend({
// here goes all the view logic to display the model data
// you can refer to your model using this.model
})
...
// in the router file
var myModel = new CountriesModel();
var router = Backbone.router.extend({
routes: {
"": home,
"home": home
},
home: function (){
var view = new CountryView({ model: myModel});
view.render(); //if you didn't rendered the view in the initialize method
}
})
Run Code Online (Sandbox Code Playgroud)
您可以在视图中访问另一个模型,并在运行时将其附加到路由器中
...
// in the router file
var myModel = new CountriesModel();
var anotherModel = new ProjectModel();
var router = Backbone.router.extend({
routes: {
"": home,
"home": home
},
home: function (){
var view = new CountryView({
model: myModel
anotherModel: anotherModel
});
view.render(); //if you didn't rendered the view in the initialize method
}
})
Run Code Online (Sandbox Code Playgroud)
并在 CountryView 中将其附加到初始化函数中
initialize: function (options){
this = _.extend(options, this)
// or
// this.anotherModel = options.anotherModel
// this.model = options.model
}
Run Code Online (Sandbox Code Playgroud)
但是您不应该在视图中混合模型,只需为项目模型创建另一个视图并在需要时使用它们
// something like
var countryView = new CountryView({model: myModel});
var projectView = new ProjectView({model: anotherModel});
Run Code Online (Sandbox Code Playgroud)
并从路由器将它们渲染在一起
| 归档时间: |
|
| 查看次数: |
760 次 |
| 最近记录: |