简体   繁体   中英

Coffeescript Backbone extends / Class Inheritance

I am trying to break out some methods that I am using across my backbone models, and I don't understand why it isn't working.

base_class.js.coffee

class MyApp.Models.BaseClass extends Backbone.Model

Linked: () =>
  @._linked

Link: (form) =>
  if @._linked == false
    $(form).backboneLink(@, {'prefixed':true})
    @._linked = true
  else
    $(form).backbonePopulate(@, {'prefixed':true})

Dirty: () ->
  @collection.Dirty()
  @._dirty = true

Clean: () ->
  @._dirty = false

isDirty: () =>
  @._dirty

page.js.coffee

#= require ./base_class

class MyApp.Models.Page extends MyApp.Models.BaseClass

  initialize: () ->
    console.log('Page Object initialized')
    @._dirty = false
    @changes = []
    @.name = 'Page'
    @._linked = false

 url: () ->
    '/pages/' + @id

However when I go into the console

page = new MyApp.Models.Page();    #=> Page Object initialized
page.Link($('#myform'));   #=>  Uncaught TypeError: Object #<Page> has no method 'Link'

I dont understand why the methods aren't being inherited.

Here is a jsfiddle of the issue: http://jsfiddle.net/Y9bPX/11/

Your indentation is off. Your CoffeeScript looks like this:

class MyApp.Models.BaseClass extends Backbone.Model

Linked: () =>
  @._linked
#...

but it should look like this:

class MyApp.Models.BaseClass extends Backbone.Model

  Linked: () =>
    @._linked
  #...

Your lack of indentation gives you an empty MyApp.Models.BaseClass and then a bunch of inaccessible functions inside an anonymous object in the JavaScript:

// CoffeeScript boilerplate...
MyApp.Models.BaseClass = (function(_super) {
  // Standard CoffeeScript class boilerplate...
})(Backbone.Model);

({
  Linked: function() {
    return _this._linked;
  },
  // etc...
});

So fix your indentation in your MyApp.Models.BaseClass and you should be fine. Remember that the entire block structure of CoffeeScript is based on the indentation so if you don't have your indentation right then you have a bunch of nonsense.

If your test code is as you posted it (and the namespace differences on the classes is a pasting mistake) , the error is that you're not calling the constructor on Page, instead you're making a reference to it:

page = new MyApp.Models.Page;

should be

page = new MyApp.Models.Page();

Check it out here (open a console):

http://jsfiddle.net/Y9bPX/3/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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