Backbone.Mutators icon indicating copy to clipboard operation
Backbone.Mutators copied to clipboard

Can't override getter - Maximum call stack size exceeded

Open jurgens opened this issue 11 years ago • 9 comments

Test = Backbone.Model.extend

  defaults:
    name: ''

  mutators:
    name: ->
      @get('name') + ' mutated'

test = new Test
#> Maximum call stack size exceeded 

jurgens avatar Aug 16 '14 13:08 jurgens

Should work, unless Coffescript does something weird in terms of scoping... Try in vanilla JavaScript & please report if the issue still persists.

asciidisco avatar Aug 18 '14 08:08 asciidisco

I'm having the same issue using vanilla JavaScript

madtrick avatar Oct 03 '14 16:10 madtrick

Same issue for me

RomanKapitonov avatar Dec 21 '14 16:12 RomanKapitonov

I think I had the same problem but solved it like this :

var User = Backbone.Model.extend({
  "mutators": {
    /**
     * Profile mutator, creates a profile model from the existing data
     * 
     * @return {Profile} Profile model instance
     */
    "profile": function() {
      // /!\ Access attributes object instead of calling this.get("profile")
      var profile = this.attributes.profile;

      if (_.isObject(profile) && !profile.cid) {
        var newProfile = new Profile();

        // Check if the existing data only consists of an id or not
        if (Object.keys(profile).length === 1 && profile.id) {
          // Only set the id
          newProfile.set("id", profile.id);
        } else {
          // Create profile model instance from existing data
          newProfile.set(profile);
        }

        profile = newProfile;

        this.set("profile", newProfile);
      }

      return profile;
    }
  }
});

I used mutators to implement nested model instances, but when using this.get("profile") inside the profile mutator I had the same error. Infinit method loop I guessed.

ghost avatar Dec 22 '14 09:12 ghost

@asciidisco I believe the issue is still present in vanilla JavaScript. I've put together a simple JSFiddle here to demonstrate. The code is a straight copy-and-paste from the Backbone.Mutators docs.

It throws an Uncaught RangeError: Maximum call stack size exceeded because it just keeps calling the mutated getter recursively forever.

Maybe we could pass in the original Backbone getter as an argument to use within the mutated getter? For example, similar to how it's currently done with setters.

For now, an easy workaround is to just use a different name for your mutated getter. But it would be nice to be able to use the same name as an existing model property.

danielmcormond avatar Jan 08 '15 16:01 danielmcormond

+1 same issue

mmrcdx avatar Feb 24 '15 06:02 mmrcdx

Same here

HiroAgustin avatar Mar 27 '15 17:03 HiroAgustin

@RasCarlito 's solution works for me +1

passabilities avatar Oct 17 '15 04:10 passabilities

Yup, same here. Still broken. @RasCarlito 's solution does work.

cnobile2012 avatar Apr 02 '17 04:04 cnobile2012