如何通过backbone.js中的全局变量创建集合? [英] How to create collection through global variable in backbone.js?

查看:46
本文介绍了如何通过backbone.js中的全局变量创建集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在stackoverflow中得到了许多顾问的帮助,部分问题已经解决,但仍然存在一些问题。



我咨询了答案,我试图通过它来解决问题我理解了javascript命名空间模式。





我认为这一代已经完成了。

但我不明白为什么我得到这个错误。



我先试过了吗?
1.不要用新函数生成集合(作为当前我的来源)

2.创建变量 videoList as Object。

3.存储集合在变量中。

4.使用collection.create函数。

例如, list.create( {id:'dasdsad'});



然而,这次尝试最终产生了相同的结果。

我如何解决这些问题?

解决方案

命名空间模式的目的是什么?



你误用了这个名字空间格局。这种情况的目标是将所有自定义Backbone类构造函数命名为 app 对象。



为了保持所有内容清晰分离,将所有集合构造函数放入 app.Collection 对象, app.Model 中的模型构造函数,等等。



如果在创建所有类之后检查 app 命名空间,它应如下所示:

  var app = {
Collection:{
VideoList:/ * video list constructor * /
},
型号:{
视频:/ *视频模型构造函数* /
},
查看:{
/ *视图相同的东西* /
}
};

app namespace shouldn' t 1 包含实例,主要是构造函数。



不要覆盖构造函数引用:

  app.Model = new models.Video(); 

只在需要时创建一个实例,并将其保存在所需的范围内。

  this.model = new app.Model.Video(); 
this.collection = app.Collection.VideoList();



实例和构造函数



真正理解前一点,您需要了解构造函数和实例之间的差异。这个概念适用于其他OOP语言,但我会将描述保持在JavaScript语言细节中。



构造函数只是一个函数。来自 MDN doc Object.prototype.constructor


所有对象都有构造函数属性。



[...]



以下示例创建原型,,以及
类型的对象, theTree

  function Tree(name){
this.name = name;
}

var theTree = new Tree('Redwood');


如前例所示,要创建实例,请使用 new 运营商 JavaScript中的'new'关键字是什么?


new运算符创建一个用户定义对象类型的实例或者一个具有构造函数的内置对象类型的

  new constructor [([arguments])] 


创建自定义构造函数可以定义自定义类型(类)。有多种方法可以在JavaScript中创建更复杂的自定义类型,但这是另一种讨论。有关详细信息,请参阅如何正确在JavaScript中创建自定义对象?



幸运的是,Backbone提供了一种简单(自以为是)的方式来定义新类型, extend function 可用于所有Backbone的基本类型

  var ModelConstructor = Backbone.Model.extend({/*...* /}); 

var modelInstance = new ModelConstructor();

请注意 myVariable = MyConstructor 将通过构造函数对 myVariable 的引用,它不会创建新实例。你仍然可以使用变量作为构造函数。

  var myInstance = new myVariable(); 



订购和依赖



如果你看在您的代码中,您会注意到 app.Collection.VideoList 类使用 app.Model.Video 作为模型属性的值。



这意味着 app.Collection.VideoList 取决于 app.Model.Video 类的可用性。因此,应该在模型文件之后将集合文件插入到文档中。



类似于我的另一个答案你链接:

 < script src =js / models / todo。 js>< / script><! - 没有依赖关系 - > 
< script src =js / collections / todos.js>< / script><! - 取决于型号 - >
< script src =js / views / todo-view.js>< / script><! - 取决于集合和模型 - >
< script src =js / views / app-view.js>< / script><! - 取决于todo-view - >
< script src =js / routers / router.js>< / script><! - 取决于应用视图 - >
< script src =js / app.js>< / script><! - 取决于路由器 - >






1。 app 命名空间对象如果要在所有应用程序(如单例,命名空间全局或服务)之间共享,则可以包含对象的实例。


I am sent the assistance by many advisors in stackoverflow, In part of my problem is solved but a few problems are remained.

I consult the answer and I has try to solve the problem as a result from it i understood the javascript namespacing pattren.

A namespacing pattern to avoid polluting the global namespace.
More details on this namespacing pattern
How do I declare a namespace in JavaScript?

I suffer from problem that global variable is created successfully however, i don't handle the generated variable.

collecton.js

    var app = app || {};
(function () {
    'use strict';
    var collections = app.Collection = app.Collection || {};

    collections.VideoLists =  Backbone.Collection.extend({
        model: app.Model,
        initialize: function(){
            console.log('load Collection');
        }
    });

    app.Collection = collections.VideoLists;
})();

model.js

var app = app || {};
(function() {
    'use strict';
    var models = app.Model = app.Model || {};

    models.Video = Backbone.Model.extend({
        initialize: function(){
            console.log('model create');
        },
        defaults:{
                 id : "1",
                 url : "/assets/videos/call/MOV01718.mp4",
                 imgSrc : "assets/img/call/1_thumbnail.png",
                 title: "call situation conservation"
        }
    });
  app.Model = new models.Video();
})();

router.js

listRoute: function(id) {
          //generate the collection using the listsection
          var videoList = this.collection;
          var getId = parseInt(id);
            switch (getId) {
              case 1:
                new videoList([
                    {
                      id : "1",
                      url : "/assets/videos/call/MOV01718.mp4",
                      imgSrc : "assets/img/call/1_thumbnail.png",
                      title: "call situation conservation"
                    },
                    {
                      id : "2",
                      url : "/assets/videos/call/MOV01722.mp4",
                      imgSrc : "assets/img/call/2_thumbnail.png",
                      title: "call situation conservation"
                    }
                  ]);
                break;

  //app.router init part
  initialize: function() {
            // create the layout once here
            this.layout = new views.Application({
                el: 'body',
            });
            // create model and collection once here
            this.model = app.Model;
            this.collection = app.Collection;
        }

Please see the below picture

I think the generation has been done properly.
But I do not understand why I get this error.

I tried at first
1. Don't generate collection with new function (as current my source)
2. Create variable videoList as Object.
3. Stores Collection in a variable.
4. Use collection.create function.
For example, list.create({id:'dasdsad'});

However, this attempt eventually yielded the same result.
How can i solve them?

解决方案

What's the purpose of the namespacing pattern?

You are misusing the namespace pattern. The goal in this case is to namespace all your custom Backbone classes constructor into the app object.

In order to keep everything clearly separated, put all your collections constructor into the app.Collection object, models constructor within app.Model, etc.

If you inspect the app namespace after all the classes are created, it should look like the following:

var app = {
    Collection: {
        VideoList: /* video list constructor */
    },
    Model: {
        Video: /* video model constructor */
    },
    View: {
        /* same thing goes for views */
    }
};

The app namespace shouldn't1 contain instances, mainly constructors.

Do not overwrite the constructors references:

app.Model = new models.Video();

Create an instance when you need one only, and keep it in the scope it's needed.

this.model = new app.Model.Video();
this.collection = app.Collection.VideoList();

Instances and constructors

To really understand the previous point, you need to understand the differences between a constructor and an instance. The concept is applicable to other OOP languages, but I'll keep the description within the JavaScript language specifics.

A constructor is just a function. From the MDN doc on Object.prototype.constructor:

All objects will have a constructor property.

[...]

The following example creates a prototype, Tree, and an object of that type, theTree.

function Tree(name) {
  this.name = name;
}

var theTree = new Tree('Redwood');

As seen in the previous example, to create an instance, use the new operator. What is the 'new' keyword in JavaScript?

The new operator creates an instance of a user-defined object type or of one of the built-in object types that has a constructor function.

new constructor[([arguments])]

Creating custom constructors lets you define custom types (classes). There are multiple ways to create more complex custom types in JavaScript but that's another discussion. For more details, see How to "properly" create a custom object in JavaScript?

Fortunately, Backbone provides an easy (opinionated) way to define new types, the extend function, which is available on all the Backbone's base types.

var ModelConstructor = Backbone.Model.extend({ /*...*/ });

var modelInstance = new ModelConstructor();

Note that myVariable = MyConstructor will just pass a reference of the constructor to myVariable, it won't create a new instance. You could still use the variable as the constructor though.

var myInstance = new myVariable();

Ordering and dependencies

If you look at your code, you'll notice that the app.Collection.VideoList class uses the app.Model.Video as the value for the model property.

This means that app.Collection.VideoList depends on the availability of the app.Model.Video class. So the collection file should be inserted into the document after the model file.

Like in the other answer of mine you linked:

<script src="js/models/todo.js"></script><!-- no dependencies -->
<script src="js/collections/todos.js"></script><!-- depends on the model -->
<script src="js/views/todo-view.js"></script><!-- depends on the collection and the model -->
<script src="js/views/app-view.js"></script><!-- depends on the todo-view -->
<script src="js/routers/router.js"></script><!-- depends on the app view -->
<script src="js/app.js"></script><!-- depends on the router -->


1. The app namespace object could contain an instance of an object if you want to share it between all your app, like a singleton, or a namespaced global, or a service.

这篇关于如何通过backbone.js中的全局变量创建集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆