开发者

Retrieving Specific Data From JSON Using a Backbone Model

I am creating a client view of an application and I need help with retrieving specific data from my JSON file. I am using Backbone.js along with Underscore.开发者_C百科js to achieve this.

(function($) {

      window.Node = Backbone.Model.extend({
         getName:    function(){
             return this.get('Name');
         } 
     });

      window.Nodes = Backbone.Collection.extend({
         model:Node,
          url: '/packageview.json'
    });

  window.NodeView = Backbone.View.extend({

    tagName: "div",

    className: "package-template",

    events:{

      "click #display-name"       :    "displayname",         
    },

    //.. I have a render and initialize function here which should not be a concern


    displayname: function(){
      var node = new Node();
      alert(node.getName());  //trying to alert
    },

  });
});

I am trying to get the name from model and alert it. I have a button in my html with an id, and when I press that button I get "undefined" as an alert. Here is how my JSON file looks:

{
  "Id": 2,
  "Name": "Some Package",
  "IsComplete": false,
  "IsNodeTagComplete": false
}

I think I am making a silly mistake somewhere. Am I expecting way to much from model?


What I am doing here is this

 window.jsonAccess = Node.extend({ // Here Node is my above mentioned model

    getJSON: function(){
        var collection = nodeInstance.toJSON(); // nodeInstance is an instance of my collection Nodes
        return collection; //returns JSON
    }
});
jAccess = new jsonAccess();

So here is what I am doing to access the JSON

 getNodeId: function(){ //Function to get Node Id from JSON
        objectJSON = jAccess.getJSON(); // Get JSON 
        _.each(objectJSON, function(action){
            _.each(action.Nodes, function(action){

This solves my purpose but not quite the way getters would be used in backbone.


Since a lot of context is missing I too may be making a mistake but here's my guess - you are creating an empty Node Model. Try doing something like this in display:

displayName: function() {

   var myJSON = window.getJSONObject(); //wherever your json object is or how to get it...
   var node = new Node({
   id:myJSON.Id,
   name:myJSON.Name,
   isComplete: myJSON.IsComplete,
   ...
   });

   alert(node.get('name'));
   alert("Getter: "+node.getName()); //your version...
}

This is just a hunch though...maybe I'm missing your context but this seems to be the case for now...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜