Backbone.js model.get() returning 'undefined' even though I can see the attributes in console.log

Asked
Active3 hr before
Viewed126 times

8 Answers

thoughundefinedreturning
90%

So it would appear that there is no issue with the object, yet the get returns undefined., Will I return at the same time I am departing on a round trip airline ticket? ,Gardening & Landscaping, What is an expedience of sci-fi gliders? these machines flying near the very ground

console.log( Object ) can cheat you. It won't show you the state of the Object in the moment of calling console.log.

console.log(Object)

console.log( Object ) can cheat you. It won't show you the state of the Object in the moment of calling console.log.

Object

console.log( Object ) can cheat you. It won't show you the state of the Object in the moment of calling console.log.

console.log
load more v
88%

console.log( Object ) can cheat you. It won't show you the state of the Object in the moment of calling console.log.,Check this jsFiddle and open the console. You see how the console.log shows you the state of the Object at the end of the script and not in the moment of the console.log call.,And make the model type of the collection be that same base model:,When I iterate over the collection to generate the list of them in the view, I get undefined when calling model.rsvp.get('attending').

Yet when I do a console.log(model.rsvp) I get this:

Rsvp
_changing: false
_escapedAttributes: Object
_moreChanges: false
_previousAttributes: Object
_setting: false
attributes: Object
attending: true
created_at: "2012-03-28T09:42:22-05:00"
event_id: 20
id: 12
updated_at: "2012-03-28T09:42:22-05:00"
user_id: 3
__proto__: Object
cid: "c53"
id: 12
__proto__: Rsvp
load more v
72%

escapemodel.escape(attribute) Similar to get, but returns the HTML-escaped version of a model's attribute. If you're interpolating data from the model into HTML, using escape to retrieve attributes will prevent XSS attacks. , Calling clear on a model now removes the id attribute. , You are no longer permitted to change the id of your model during parse. Use idAttribute instead. ,"change" (model, options) — when a model's attributes have changed.

Backbone is pre-configured to sync with a RESTful API. Simply create a new Collection with the url of your resource endpoint:

var Books = Backbone.Collection.extend({
   url: '/books'
});
load more v
65%

However, the second returns undefined despite the model attributes clearly being there in the console when logged. ,The first logging statement outputs the correct Backbone.Model attributes object in the console just as it should: ,And just to make things even more interesting, typing "window.app.user.get('email')" into the console manually returns the expected value of "ben@accomplicecreative.com"... ?,The console.log calls get around to logging things in the console.

As part of the initialization routine I grab the user from the server (which takes care of authentication, roles, account switching etc.). Here's that coffeescript:

@user = new models.User
@user.fetch()
console.log(@user)
console.log(@user.get('email'))

The first logging statement outputs the correct Backbone.Model attributes object in the console just as it should:

User
_changing: false
_escapedAttributes: Object
_pending: Object
_previousAttributes: Object
_silent: Object
attributes: Object
account: Object
created_on: "1983-12-13 00:00:00"
email: "ben@accomplicecreative.com"
icon: "0"
id: "1"
last_login: "2012-06-07 02:31:38"
name: "Ben Ipsen"
roles: Object
__proto__: Object
changed: Object
cid: "c0"
id: "1"
__proto__: ctor
app.js: 228

Just for reference, here's how the initialize method compiles into my app.js file:

Application.prototype.initialize = function() {
   var isMobile;
   isMobile = navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry)/);
   this.helpers = new views.DOMHelpers().initialize().setup_viewport(isMobile);
   this.user = new models.User();
   this.user.fetch();
   console.log(this.user);
   console.log(this.user.get('email'));
   return this;
};

I initialize the Application controller in my static HTML like so:

jQuery(document).ready(function() {
   window.app = new controllers.Application();
});
load more v
75%

After the initial render the CollectionView binds to the update and reset events of the collection.,If you wish to add a child view to the children without the collectionview rendering the children use the preventRender option.,Rendering a CollectionView Rendering a Template Defining the childViewContainer Re-rendering the CollectionView ,If emptyViewOptions aren't provided the CollectionView will default to passing the childViewOptions to the emptyView.

When instantiating a CollectionView there are several properties, if passed, that will be attached directly to the instance: attributes, behaviors, childView, childViewContainer, childViewEventPrefix, childViewEvents, childViewOptions, childViewTriggers, className, collection, collectionEvents, el, emptyView, emptyViewOptions, events, id, model, modelEvents, sortWithCollection, tagName, template, templateContext, triggers, ui, viewComparator, viewFilter

import {
   CollectionView
} from 'backbone.marionette';

const myCollectionView = new CollectionView({
   ...
});
load more v
40%

You're browsing the Backbone.js documentation. To browse all docs, go to devdocs.io (or press esc). , We would like to gather usage data about how DevDocs is used through Google Analytics and Gauges. We only collect anonymous traffic information. Please confirm if you accept our tracking cookies. You can always change your decision in the settings. Accept or Decline Close

You're browsing the Backbone.js documentation. To browse all docs, go to devdocs.io (or press esc).

esc
22%

Backbone.js model.get() returning 'undefined' even though I can see the attributes in console.log,Backbone.js Empty Array Attribute,Asked By: Anonymous I’m trying to make a higher order component with Typescript, but I’m getting a type mismatch. I completely stripped it down, so it should just wrap the component, but still getting the...,You should modify a little bit your architecture and assigns a proper View to each Joke, so you can have for each Joke a View that is taking care of show it when is needed.

Im using backbone to construct my client-side app, what im trying to do is is display a joke each time the user clicks .get_joke on an event: heres my backbone app code:

JokeModel = Backbone.Model.extend({
   url: '/jokes'
   initialize: function() {
      this.fetch();
  }
});

JokeView = Backbone.View.extend({
    template: _.template("<p><%= joke %></p>")
    events: {
      "click .get_joke" : "render"
  } 
    render: function() {
       var newJoke = new JokeModel;
       $(this.el).html(this.template(newJoke.toJSON()));
  }
});

newJokeView = new JokeView;
load more v
60%

Patterns can be expressive: When we look at a pattern there’s generally a set structure and vocabulary to the solution presented that can help express rather large solutions quite elegantly.,Decorators are a structural design pattern that aim to promote code re-use. Similar to Mixins, they can be considered another viable alternative to object sub-classing.,Patterns can be easily reused: A pattern usually reflects an out of the box solution that can be adapted to suit our own needs. This feature makes them quite robust., To understand how useful patterns can be, let's review a very simple element selection problem that the jQuery library solves for us.

The most common approach to achieving this is by defining a JavaScript function where we then create an object using the new keyword. this can be used to help define new properties and methods for the object as follows:

// A car "class"
function Car(model) {

   this.model = model;
   this.color = "silver";
   this.year = "2012";

   this.getInfo = function() {
      return this.model + " " + this.year;
   };

}

We can then instantiate the object using the Car constructor we defined above like this:

var myCar = new Car("ford");

myCar.year = "2010";

console.log(myCar.getInfo());

// Each of the following options will create a new empty object:

var newObject = {};

// or
var newObject = Object.create(Object.prototype);

// or
var newObject = new Object();

// ECMAScript 3 compatible approaches

// 1. Dot syntax

// Set properties
newObject.someKey = "Hello World";

// Get properties
var value = newObject.someKey;

// 2. Square bracket syntax

// Set properties
newObject["someKey"] = "Hello World";

// Get properties
var value = newObject["someKey"];

// ECMAScript 5 only compatible approaches
// For more information see: http://kangax.github.com/es5-compat-table/

// 3. Object.defineProperty

// Set properties
Object.defineProperty(newObject, "someKey", {
   value: "for more control of the property's behavior",
   writable: true,
   enumerable: true,
   configurable: true
});

// If the above feels a little difficult to read, a short-hand could
// be written as follows:

var defineProp = function(obj, key, value) {
   var config = {
      value: value,
      writable: true,
      enumerable: true,
      configurable: true
   };
   Object.defineProperty(obj, key, config);
};

// To use, we then create a new empty "person" object
var person = Object.create(Object.prototype);

// Populate the object with properties
defineProp(person, "car", "Delorean");
defineProp(person, "dateOfBirth", "1981");
defineProp(person, "hasBeard", false);

console.log(person);
// Outputs: Object {car: "Delorean", dateOfBirth: "1981", hasBeard: false}

// 4. Object.defineProperties

// Set properties
Object.defineProperties(newObject, {

   "someKey": {
      value: "Hello World",
      writable: true
   },

   "anotherKey": {
      value: "Foo bar",
      writable: false
   }

});

// Getting properties for 3. and 4. can be done using any of the
// options in 1. and 2.

// Usage:

// Create a race car driver that inherits from the person object
var driver = Object.create(person);

// Set some properties for the driver
defineProp(driver, "topSpeed", "100mph");

// Get an inherited property (1981)
console.log(driver.dateOfBirth);

// Get the property we set (100mph)
console.log(driver.topSpeed);

function Car(model, year, miles) {

   this.model = model;
   this.year = year;
   this.miles = miles;

   this.toString = function() {
      return this.model + " has done " + this.miles + " miles";
   };
}

// Usage:

// We can create new instances of the car
var civic = new Car("Honda Civic", 2009, 20000);
var mondeo = new Car("Ford Mondeo", 2010, 5000);

// and then open our browser console to view the
// output of the toString() method being called on
// these objects
console.log(civic.toString());
console.log(mondeo.toString());

function Car(model, year, miles) {

   this.model = model;
   this.year = year;
   this.miles = miles;

}

// Note here that we are using Object.prototype.newMethod rather than
// Object.prototype so as to avoid redefining the prototype object
Car.prototype.toString = function() {
   return this.model + " has done " + this.miles + " miles";
};

// Usage:

var civic = new Car("Honda Civic", 2009, 20000);
var mondeo = new Car("Ford Mondeo", 2010, 5000);

console.log(civic.toString());
console.log(mondeo.toString());
load more v

Other "though-undefined" queries related to "Backbone.js model.get() returning 'undefined' even though I can see the attributes in console.log"