简体   繁体   English

如何在jQuery范围内使用Backbone模型

[英]How to use a Backbone model with jQuery concerning scope

I have a jQuery project where I am looking to maintain form data inside model variables. 我有一个jQuery项目,我正在其中维护模型变量中的表单数据。 My current UI code is like this 我当前的UI代码是这样的

$(document).ready(function(){
    $("#errMsg").hide();

    var Test = Backbone.Model.extend({
            defauts: {
                id: null,
                test: null,
                test1: null,
                test2: null,
                comments: null
            }
        });

     var uniquename = new Test({ id: null});


});

function test(){
  //Trying to access uniquename here or Test model
}

When I try to access either Test or uniquename from the method outside, they're not accessible. 当我尝试从外部方法访问Test或uniquename时,将无法访问它们。 All the other stuff I do is inside plain Javascript methods. 我做的所有其他事情都在普通的JavaScript方法中。 I know this is not the right way to do it so i'm seeking some help. 我知道这不是正确的方法,因此我正在寻求帮助。 How do I structure my methods and how do I make my variables accessible across different methods so I can read the web service response from one method and use that as a request for another method? 如何构造我的方法,如何使变量可跨不同方法访问,以便可以从一个方法读取Web服务响应并将其用作对另一个方法的请求?

Simply define the function inside the same scope: 只需在相同范围内定义函数:

$(document).ready(function(){

  $("#errMsg").hide();

  var Test = Backbone.Model.extend({
        defauts: {
            id: null,
            test: null,
            test1: null,
            test2: null,
            comments: null
        }
    });

    var uniquename = new Test({ id: null});
    function test(){
       //access uniquename here or Test model
    }
});

If you can't do that, for example if your code is split into different files or something, then simplest solution would be to use name spaces - like MyApp.Models.Test = Backbone.Model.extend({}) . 如果您无法执行此操作(例如,如果代码被拆分为不同的文件或其他内容),则最简单的解决方案是使用名称空间-例如MyApp.Models.Test = Backbone.Model.extend({}) MyApp in this case will be globally available (declared outside $(document).ready() in the file that is loaded first ) 在这种情况下, MyApp将在全球范围内可用(在首先加载的文件的$(document).ready()外部声明)。

or use module pattern, RequireJS is pretty common module loader in Backbone.js applications. 或使用模块模式,RequireJS是Backbone.js应用程序中非常常见的模块加载器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM