lelandrichardson / knockout-oftype

Some Extensions and Helpers for handling the Constructor pattern in Knockout
8 stars 1 forks source link

Extensibility example #1

Closed dev101 closed 11 years ago

dev101 commented 11 years ago

Hi Leland, thanks for making this extension, this is really a missing piece in KO!

Could you provide some extensibility examples (maybe in a separate file)?

I want to edit my objects in a table-like grid editor, and need add more array functions (to assign as row-level actions to manipulate array members):

(as I have dozens of object types, and don't wont to implement these methods for each type).

I can see you provided extensibility endpoint, but am reluctant to use it being not familiar with KO's extenders syntax.

I believe making such example would take minutes of your time, and would be very useful for users of knockout-oftype!

lelandrichardson commented 11 years ago

Hi @dev101 - no problem! Sorry for not getting back sooner, my notification emails for github seem to keep getting buried.

the line you referenced:

ko.observableArray.fn.ofType.fn = newMethods;

is used in the .ofType "constructor" function as seen here:

extend(interceptor, newMethods);

which basically means that whatever methods you "tack on" to ko.observableArray.fn.ofType.fn, they will be present on instances of those observable arrays.

For example, typically in JS to provide one of your extender methods like you've done above, you might do the following:

Array.prototype.insertAbove = function(index){
    return this.splice(index,0,{});
};

To provide the same behavior to the observable arrays, you would simply use:

ko.observableArray.fn.ofType.fn.insertAbove = function(index){
    return this.splice(index,0,{}); // in this case, `this` is the ko.observableArray().ofType() instance
};

Is that any more clear? I can go into more detail if you'd like.

dev101 commented 11 years ago

well, i tried that insertAbove example, but got an error at line #24. See the fiddle.

dev101 commented 11 years ago

I think found the reason - a typo in splice(). See pull request https://github.com/lelandrichardson/knockout-oftype/pull/2

dev101 commented 11 years ago

You may want to refer to this fiddle in documentation as example featuring usage of ofType extensions along with delegatedEvents plugin to create type-agnostic grid actions widget operating across different kinds of typed objects.

Thanks again for plugin.