BackboneJS - Collection Url

描述

它创建集合的实例并返回资源所在的位置。

语法

collection.url()

示例

<!DOCTYPE html>
<html>
   <head>
      <title>Collection Example</title>
      <script src = "https://code.jquery.com/jquery-2.1.3.min.js"
         type = "text/javascript"></script>
      
      <script src = "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js"
         type = "text/javascript"></script>
      
      <script src = "https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js"
         type = "text/javascript"></script>
   </head>
   
   <body>
      <script type = "text/javascript">
         var MyModel = Backbone.Model.extend({});  ////'MyModel' is a model name

        //"MyCollection"是集合的一个实例
        var MyCollection = Backbone.Collection.extend ({
            model: MyModel //通过覆盖"model"属性指定模型"MyModel"
        });
        
        //模型"MyBlog"包含"user"和"myposts"属性的默认值
         var MyBlog = Backbone.Model.extend ({
            defaults: {
               user: null,
               myposts: []
            },
            initialize: function () {
               var myval = this;

				//模型"MyModel"通过引用当前对象从模型"MyBlog"中获取"user"和"myposts"
               this.MyModel = new MyModel(this.get('user'));
               this.posts = new MyCollection(this.get('myposts'));
               
               this.posts.url = function () {
                  return myval.url() + '/myposts';
               };
            },

            //它通过使用 id 属性来启用 url() 函数
            //生成 URL 作为"/MyBlog/50/myposts/26"
            urlRoot: '/MyBlog/'
         });
         var attributes = {
            id: 50,
            myposts:[{id: 26}]
         }

         //模型"MyBlog"将访问属性并使用"url()"函数显示 url
         val = new MyBlog(attributes);
         
         val.posts.each(function (MyModel) {
            document.write("The url pattern is: ",MyModel.url());
         });
      </script>
      
   </body>
</html>

输出

让我们执行以下步骤来查看上述代码的工作原理 −

  • 将上述代码保存在 url.html 文件中。

  • 在浏览器中打开此 HTML 文件。

backbonejs_collection.html