Hello, I'm a novice JS developer and CanJS caught my attention because it does offer some of the important goodies larger frameworks like Ember or Angular offer, but without the framework part. And the fact that it seems easy to integrate with 3rd party libraries was another plus.
As for my problem: I can't say i'm a fan of the obj.attr('some_property',value) signature. It's not a big deal, but I've been wondering if it's possible to modify how can.Map works so that it would create getters and setter that circumvent the .attr method, so that instead of calling obj.attr('Title','Noah's Arc'), you'd just use obj.Title = 'Noah's Arc', with the benefits that can.Map brings to the table.
So, after googling on the webz to see what IE friendly getter/setter implementation I could find, i stumbled upon the following:
And used it like this:
- var NativeMap = can.Construct.extend({}, {
- setup: function (obj) {
- var self = this;
- var properties = [];
- for (var key in obj) {
- if (obj.hasOwnProperty(key) || hasPropertyInChain(obj, key)) {
- if (typeof obj[key] !== 'function') {
- properties.push(key);
- }
- else
- {
- this[key] = obj[key];
- }
- }
- }
- var justMembers = {};
- for (var i = 0; i < properties.length; i++) {
- justMembers[properties[i]] = obj[properties[i]];
- }
- this.map = new can.Map(justMembers);
- for (var member in this.map._data) {
- (function(objToMutate,memberName){
- getset(function () {
- Object.defineProperty(objToMutate, memberName, {
- get: function () {
- return this.map.attr(memberName);
- },
- set: function (val) {
- this.map.attr(memberName, val);
- }
- });
- });
- })(self,member);
- }
- },
- bind: function (event, fn) {
- this.map.bind(event, fn);
- return this;
- }
- });
And used it like this with success:
- var somePagination= new NativeMap({
- page: 1,
- perPage: 25,
- count: 1388,
- next: function () {
- this.page = this.page + 1;
- }
- });
- somePagination.bind('change', function (event, attr, how, newVal, oldVal) {
- console.log("Native setter from " + oldVal + " to " + newVal);
- });
- somePagination.perPage = 4444; //will output "Native setter From 25 to 4444"
- somePagination.next();// will output "Native setter from 25 to 4444"
- console.log(somePagination.perPage);
Unfortunately, if I use can.NativeMap.Extend({...}), this doesn't work anymore, since the object which we gave to the Extend method is already merged with the can.NativeMap.Extend({}) result. I've read the canJS codebase, and I really can't figure out how to fix this. Any tips? Thanks in advance.