cc.Class.extend not respecting functions - cocos2d-x

When ever I run the code below in Cocos 2D HTML or with bindings it seems to not add any of my functions but will add my Variables.
So:
cc.Class.extend({
init: function(isDancing){
this.dancing = isDancing;
},
age : 5,
dance: function(){
return this.dancing;
}
});
becomes :
function anonymous() {
this._super=null;this.age=this.age;
}
Which I will get a undefined error when I try to call, dance().

constructor function is 'ctor'(not 'init')
var Klass = cc.Class.extend({
ctor: function(isDancing){
this.dancing = isDancing;
},
age : 5,
dance: function(){
return this.dancing;
}
});
undefined
var el = new Klass(22);
undefined
el.dance()
22

Related

Variable scope & Callback woes

This program is reading through the nested object searching for a specific key & values. Once this data is found it has to initiate callback to send back the data. The object looks like this:
{
"name": "joel",
"title": "CTO",
"edu": {
"school": "RMB",
"college": "GNK",
"pg": "CDAC",
"extract": "This is a large text ..."
}
}
Here as I come from synchronous programming background I am not able to understand when I have to initiate the callback and also ensure variables are in scope
function parseData(str, callback) {
function recursiveFunction(obj) {
var keysArray = Object.keys(obj);
for (var i = 0; i < keysArray.length; i++) {
var key = keysArray[i];
var value = obj[key];
if (value === Object(value)) {
recursiveFunction(value);
}
else {
if (key == 'title') {
var title = value;
}
if (key == 'extract') {
var extract = value.replace(/(\r\n|\n|\r)/gm," ");
callback(null, JSON.stringify({title: title, text: extract}));
}
}
}
}
recursiveFunction(str, callback(null, JSON.stringify({title: title, text: extract})));
};
when this code is executed we get following error
/parseData.js:29
recursiveFunction(str, callback(null, JSON.stringify({title: title, text: extract})));
^
ReferenceError: title is not defined
Okay. So you want a function that retrieves the first property named title and the first property named extract from a nested object, no matter how deeply nested these properties are.
"Extract a property value from an object" is basically is a task in its own right, we could write a function for it.
There are three cases to handle:
The argument is not an object - return undefined
The argument contains the key in question - return the associated value
Otherwise, recurse into the object and repeat steps 1 and 2 - return according result
It could look like this:
function pluck(obj, searchKey) {
var val;
if (!obj || typeof obj !== "object") return;
if (obj.hasOwnProperty(searchKey)) return obj[searchKey];
Object.keys(obj).forEach(function (key) {
if (val) return;
val = pluck(obj[key], searchKey);
});
return val;
}
Now we can call pluck() on any object and with any key and it will return to us the first value it finds anywhere in the object.
Now the rest of your task becomes very easy:
var obj = {
"name": "joel",
"title": "CTO",
"edu": {
"school": "RMB",
"college": "GNK",
"pg": "CDAC",
"extract": "This is a large text ..."
}
}
var data = {
title: pluck(obj, "title"),
text: pluck(obj, "extract")
};
This function that you 've posted above has nothing to do with async programming. I will respond in the context of the chunk of code that you 've posted. The error that you have is because you are calling the recursiveFunction(str, callback(null, JSON.stringify({title: title, text: extract}))); but the title variable is nowhere defined. I can see a definition of the title but it is in the the context of the recursiveFunction function. The variables that you define in there are not visible outside of the scope of that function and that's why you have this error.
You are trying to do something strange in this line:
recursiveFunction(str, callback(null, JSON.stringify({title: title, text: extract})));
This line will invoke the callback and will pass in the recursiveFunction the results of this function. I would expect to see something like that in this line:
recursiveFunction(str, callback);

How do i test my custom angular schema form field

I've just started developing with Angular schema form and I'm struggling to write any tests for my custom field directive.
I've tried compiling the schema form html tag which runs through my directives config testing it's display conditions against the data in the schema. However it never seems to run my controller and I can't get a reference to the directives HTML elements. Can someone give me some guidance on how to get a reference to the directive? Below is what I have so far:
angular.module('schemaForm').config(['schemaFormProvider',
'schemaFormDecoratorsProvider', 'sfPathProvider',
function(schemaFormProvider, schemaFormDecoratorsProvider, sfPathProvider) {
var date = function (name, schema, options) {
if (schema.type === 'string' && schema.format == 'date') {
var f = schemaFormProvider.stdFormObj(name, schema, options);
f.key = options.path;
f.type = 'date';
options.lookup[sfPathProvider.stringify(options.path)] = f;
return f;
}
};
schemaFormProvider.defaults.string.unshift(date);
schemaFormDecoratorsProvider.addMapping('bootstrapDecorator', 'date',
'app/modules/json_schema_form/schema_form_date_picker/schema_form_date_picker.html');
}]);
var dateControllerFunction = function($scope) {
$scope.isCalendarOpen = false;
$scope.showCalendar = function () {
$scope.isCalendarOpen = true;
};
$scope.calendarSave = function (date) {
var leaf_model = $scope.ngModel[$scope.ngModel.length - 1];
var formattedDate = $scope.filter('date')(date, 'yyyy-MM-dd');
leaf_model.$setViewValue(formattedDate);
$scope.isCalendarOpen = false;
};
};
angular.module('schemaForm').directive('schemaFormDatePickerDirective', ['$filter', function($filter) {
return {
require: ['ngModel'],
restrict: 'A',
scope: false,
controller : ['$scope', dateControllerFunction],
link: function(scope, iElement, iAttrs, ngModelCtrl) {
scope.ngModel = ngModelCtrl;
scope.filter = $filter
}
};
}]);
<div ng-class="{'has-error': hasError()}">
<div ng-model="$$value$$" schema-form-date-picker-directive>
<md-input-container>
<!-- showTitle function is implemented by ASF -->
<label ng-show="showTitle()">{{form.title}}</label>
<input name="dateTimePicker" ng-model="$$value$$" ng-focus="showCalendar()" ng-disabled="isCalendarOpen">
</md-input-container>
<time-date-picker ng-model="catalogue.effectiveFrom" ng-if="isCalendarOpen" on-save="calendarSave($value)" display-mode="date"></time-date-picker>
</div>
<!-- hasError() defined by ASF -->
<span class="help-block" sf-message="form.description"></span>
</div>
And the spec:
'use strict'
describe('SchemaFormDatePicker', function() {
var $compile = undefined;
var $rootScope = undefined;
var $scope = undefined
var scope = undefined
var $httpBackend = undefined;
var elem = undefined;
var html = '<form sf-schema="schema" sf-form="form" sf-model="schemaModel"></form>';
var $templateCache = undefined;
var directive = undefined;
beforeEach(function(){
module('app');
});
beforeEach(inject(function(_$compile_, _$rootScope_, _$templateCache_, _$httpBackend_) {
$compile = _$compile_
$rootScope = _$rootScope_
$httpBackend = _$httpBackend_
$templateCache = _$templateCache_
}));
beforeEach(function(){
//Absorb call for locale
$httpBackend.expectGET('assets/locale/en_gb.json').respond(200, {});
$templateCache.put('app/modules/json_schema_form/schema_form_date_picker/schema_form_date_picker.html', '');
$scope = $rootScope.$new()
$scope.schema = {
type: 'object',
properties: {
party: {
title: 'party',
type: 'string',
format: 'date'
}}};
$scope.form = [{key: 'party'}];
$scope.schemaModel = {};
});
describe("showCalendar", function () {
beforeEach(function(){
elem = $compile(html)($scope);
$scope.$digest();
$httpBackend.flush();
scope = elem.isolateScope();
});
it('should set isCalendarOpen to true', function(){
var result = elem.find('time-date-picker');
console.log("RESULT: "+result);
));
});
});
});
If you look at the below example taken from the project itself you can see that when it uses $compile it uses angular.element() first when setting tmpl.
Also, the supplied test module name is 'app' while the code sample has the module name 'schemaForm'. The examples in the 1.0.0 version of Angular Schema Form repo all use sinon and chai, I'm not sure what changes you would need to make if you do not use those.
Note: runSync(scope, tmpl); is a new addition for 1.0.0 given it is now run through async functions to process $ref includes.
/* eslint-disable quotes, no-var */
/* disabling quotes makes it easier to copy tests into the example app */
chai.should();
var runSync = function(scope, tmpl) {
var directiveScope = tmpl.isolateScope();
sinon.stub(directiveScope, 'resolveReferences', function(schema, form) {
directiveScope.render(schema, form);
});
scope.$apply();
};
describe('sf-array.directive.js', function() {
var exampleSchema;
var tmpl;
beforeEach(module('schemaForm'));
beforeEach(
module(function($sceProvider) {
$sceProvider.enabled(false);
exampleSchema = {
"type": "object",
"properties": {
"names": {
"type": "array",
"description": "foobar",
"items": {
"type": "object",
"properties": {
"name": {
"title": "Name",
"type": "string",
"default": 6,
},
},
},
},
},
};
})
);
it('should not throw needless errors on validate [ノಠ益ಠ]ノ彡┻━┻', function(done) {
tmpl = angular.element(
'<form name="testform" sf-schema="schema" sf-form="form" sf-model="model" json="{{model | json}}"></form>'
);
inject(function($compile, $rootScope) {
var scope = $rootScope.$new();
scope.model = {};
scope.schema = exampleSchema;
scope.form = [ "*" ];
$compile(tmpl)(scope);
runSync(scope, tmpl);
tmpl.find('div.help-block').text().should.equal('foobar');
var add = tmpl.find('button').eq(1);
add.click();
$rootScope.$apply();
setTimeout(function() {
var errors = tmpl.find('.help-block');
errors.text().should.equal('foobar');
done();
}, 0);
});
});
});

BackboneJS - fetching collections from model

I have a JSON file which basically looks like this:
[
{
"First" : [...]
},
{
"Second" : [...]
},
{
"Third" : [...]
},
]
In my router i have:
this.totalCollection = new TotalCollection();
this.totalView = new TotalView({el:'#subContent', collection:this.totalCollection});
this.totalCollection.fetch({success: function(collection) {
self.totalView.collection=collection;
self.totalView.render();
}});
Now i have my Backbone Model:
define([
"jquery",
"backbone"
],
function($, Backbone) {
var TotalModel = Backbone.Model.extend({
url: "/TotalCollection.json",
initialize: function( opts ){
this.first = new First();
this.second = new Second();
this.third = new Third();
this.on( "change", this.fetchCollections, this );
},
fetchCollections: function(){
this.first.reset( this.get( "First" ) );
this.second.reset( this.get( "Second" ) );
this.third.reset( this.get( "Third" ) );
}
});
return TotalModel;
});
and my in my Backbone View i try to render the collection(s):
render: function() {
$(this.el).html(this.template(this.collection.toJSON()));
return this;
}
But I get the Error "First is not defined" - whats the issue here?
Have you actually defined a variable 'First', 'Second' and 'Third'? Based on what you're showing here, there is nothing with that name. One would expect you to have a couple lines like..
var First = Backbone.Collection.extend({});
var Second = Backbone.Collection.extend({});
var Third = Backbone.Collection.extend({});
However you haven't provided anything like that, so my first assumption is that you just haven't defined it.
Per comments, this may be more what you need:
render: function() {
$(this.el).html(this.template({collection: this.collection.toJSON())});
return this;
}
Then..
{{#each collection}}
{{#each First}}
/*---*/
{{/each}}
{{/each}}

yeoman generator : repeat a prompt

i'm create a custom yeoman generator, i need create an array base on user responses :
How can i repeat a question and push answer to an array ?
ex :
Add a value ? Y/n
if yes
Value = ?
Add a value ? Y/n
...
for the moment, i have this code :
MyGenerator.prototype.askFor = function askFor() {
var cb = this.async();
console.log(this.yeoman);
var prompts = [
{
type: 'confirm',
name: 'addvalue',
message: 'Add value ?',
default: true
},
{
name: 'myarray',
message: 'Value =',
}
];
this.prompt(prompts, function (props) {
this.addvalue = props.addvalue;
cb();
}.bind(this));
};
Just use a recursive function.
example (won't work as is because of this context):
function askSomething() {
this.prompt({ /* some prompts */ }, function (answers) {
// call the function back if needed
askSomething();
});
}

Json and lawnchair usage

i saw below example in lawnchair documentation,
var store = new lawnchair({name:'testing'}, function(store) {
// create an object
var me = {key:'brian'};
// save it
store.save(me);
// access it later... yes even after a page refresh!
store.get('brian', function(me) {
console.log(me);
});
});
i am not sure i understood it correctly or not, but based on my understanding, i wrote code like this, (name,dtime,address are variables with value)
db = Lawnchair({
name : 'db'
}, function(store) {
console.log('storage open');
var formDetails = {
"candidateName" : name,
"DateTimeOfVerification" : dtime,
"ResidentialAddress" : address
}
store.save({key:"fdetails",value:formDetails});
store.get("fdetails", function(obj) {
alert(obj);
});
});
but, in alert i did not got value, i got "[object Object]".
1) how to store multi-attribute json object in lawnchair
2) how to get that json object.
Try this:
db = Lawnchair({name : 'db'}, function(store) {
console.log('storage open');
var formDetails = {
"candidateName" : "Viswa",
"DateTimeOfVerification" : "30/07/2012",
"ResidentialAddress" : "3 The Road, Etcc...."
}
store.save({key:"fdetails", value:formDetails});
store.get("fdetails", function(obj) {
console.log(obj);
alert(obj.value.candidateName);
alert(obj.value.DateTimeOfVerification);
alert(obj.value.ResidentialAddress)
});
});
1) You are storing the formDetails structure correctly.
2) obj.value is the collection you are looking for
Had you added the console.log(obj); line into your code and then inspected the console you could probably have worked this out for yourself.