Basic Sproutcore: class method, class variables help

286 Views Asked by At

This is how i am defining a simple class with instance variables and instance methods.

ExampleClass = SC.Object.extend({
    foo:undefined,
    bar: function() {
        this.foo = "Hello world";
        console.log( this.foo );
    }
}

// test
var testInstance = ExampleClass.create();
testInstance.bar();    // outputs 'Hello world'

Could anyone help me out with a similar example of class variable (or similar behavoir), and class method?

Thanks

1

There are 1 best solutions below

3
On BEST ANSWER

A class Method/Property would be done like:

ExampleClass = SC.Object.extend({
  foo:undefined,
  bar: function() {
    this.foo = "Hello world";
    console.log( this.foo );
  }
}

ExampleClass.mixin({
  classFoo: "foo",
  classBar: function() {
    return "Bar";
  }
})

Then you can access it like:

ExampleClass.classFoo

But don't forget that when accessing a property (or computed property) on an instance, that you need to use .get() like:

var example = ExampleClass.create();
// Good
example.get('foo');
example.set('foo', 'baz');

// BAD!! Don't do this, or Bindings/ Observes won't work.
example.foo; 
example.foo = 'baz';