Skip to content

Commit

Permalink
Set custom map on element (#20)
Browse files Browse the repository at this point in the history
* fix set custom map on element with SimpleMap

* fix set custom map on element with simple-map can-map and define-map
  • Loading branch information
Mohamed Cherif Bouchelaghem authored and phillipskevin committed May 19, 2017
1 parent 4bf7f02 commit fa25563
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
7 changes: 6 additions & 1 deletion can-view-model.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,18 @@ var ns = require("can-namespace");
var getDocument = require("can-util/dom/document/document");
var isArrayLike = require('can-util/js/is-array-like/is-array-like');
module.exports = ns.viewModel = function (el, attr, val) {
var scope ;
if (typeof el === 'string') {
el = getDocument().querySelector(el);
} else if (isArrayLike(el)) {
el= el[0];
}

var scope = domData.get.call(el, "viewModel");
if (types.isMapLike(attr)) {
return domData.set.call( el, "viewModel", attr);
}

scope = domData.get.call(el, "viewModel");
if(!scope) {
scope = types.DefaultMap ? new types.DefaultMap() : new SimpleMap();
domData.set.call(el, "viewModel", scope);
Expand Down
32 changes: 32 additions & 0 deletions can-view-model_test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
var QUnit = require('steal-qunit');
var viewModel = require('can-view-model');
var SimpleMap = require('can-simple-map');
var CanMap = require('can-map');
var DefineMap = require("can-define/map/map");
var types = require('can-types');

QUnit.module('can-view-model');
Expand All @@ -27,6 +29,36 @@ QUnit.test('a selector can be passed as the first argument (#6)', function(){
types.DefaultMap = DefaultMap;
});

QUnit.test('set custom can-simple-map on element (#5)', function(){
var vm, elVm;
var CustomMap = SimpleMap.extend({});
var el = document.createElement('div');
document.getElementById('qunit-fixture').appendChild(el);
vm = new CustomMap({ foo: 'bar' });
elVm = viewModel(el, vm);
QUnit.equal(viewModel(el,'foo'), 'bar');
});

QUnit.test('set custom can-map on element (#5)', function(){
var vm, elVm;
var CustomMap = CanMap.extend({});
var el = document.createElement('div');
document.getElementById('qunit-fixture').appendChild(el);
vm = new CustomMap({ foo: 'bar' });
elVm = viewModel(el, vm);
QUnit.equal(viewModel(el,'foo'), 'bar');
});

QUnit.test('set custom can-define-map on element (#5)', function(){
var vm, elVm;
var CustomMap = DefineMap.extend({});
var el = document.createElement('div');
document.getElementById('qunit-fixture').appendChild(el);
vm = new CustomMap({ foo: 'bar' });
elVm = viewModel(el, vm);
QUnit.equal(viewModel(el,'foo'), 'bar');
});

QUnit.test('Allow passing array like (jQuery) element', function(){
var DefaultMap = types.DefaultMap;
var $el = {};
Expand Down

0 comments on commit fa25563

Please sign in to comment.