How to send final game score between Cocos Creator scenes? - cocos2d-js

I'm trying to create a game with Cocos Creator. I'm using more than one file in the game. Like Game.js GameOver.js Jump.js etc. I'm collecting scores with GainScore.js. I have to send final score to GameOver.js file. I show the score properly during the game. But when the game is over I have to send it to the other screen. How can I use the game score as global?
My gainScore function:
gainScore() {
this.score += 1;
if (this.scoreDisplay === null) return;
this.scoreDisplay.string = this.score;
},
My GameOver.js file
cc.Class({
extends: cc.Component,
properties: {
scoreEnd: {
default: null,
type: cc.Label,
},
},
start() {
this.scoreEnd.string = this.score.toString(); // I can't access with this way
},
});

You can use CommonJS. Create a new file called Global.js.
scripts
|__ GameOver.js
|__ GainScore.js
|__ Global.js
and keep your global variables here.
Global.js:
module.exports = {
score: 0
};
And use with require in other files:
let Globals = require("Globals");
....
gainScore() {
Globals.score += 1; // not this.score, should be Globals.score
if (this.scoreDisplay === null) return;
this.scoreDisplay.string = Globals.score;
},
You should require all other files that will use
let Globals = require("Globals");
cc.Class({
extends: cc.Component,
properties: {
scoreEnd: {
default: null,
type: cc.Label,
},
},
start() {
this.scoreEnd.string = Globals.score.toString();
},
});

Related

iOS all function hook using frida

I wanna hook all functon in specific iOS app using frida
basically I tried 1 func like this
Interceptor.attach(func_address, {
onEnter: function(args) {
console.log("");
console.log("[+] hooked!");
},
onLeave: function(retval) {}
});
but I wanna automatcally hook all func with all func searching if it could
like
....
...searching 1000 funcs here it's saved in hook_func array
....
let hook_func = func_array[1000];
for(let i = 0; i < hook_func.length; i++) {
Interceptor.attach(func_array[i], {
onEnter: function(args) {
console.log("");
console.log("[+] detected somethin!");
},
onLeave: function(retval) {}
});
}
anyone try this before ...
I need your help (cry)

How to create batch using oData in SAPUI5 but I am able to create single record each time

I am not able to send batch records. But I am able to add single entity each time. I used the following function on submit.
// creating single entry each time.
onSubmitChanges: function() {
var oSelectedVal = this.getView().byId("plmSelect"),
oSelectedVal = oSelectedVal.getSelectedItem().getKey(),
oModel = this.getView().getModel(),
oEntry = {};
oEntry.MyKeyField1 = oSelectedVal;
oEntry.MyEntry1 = globalVariable1; // global variable declared to get values
oEntry.MyEntry2 = globalVariable2;
oEntry.MyEntry3 = globalVariable3;
oEntry.MyEntry4 = globalVariable4;
if (oEntry.MyKeyField1 !== "" && oEntry.MyEntry1 !== "" && oEntry.MyEntry2 !== "") {
var oContext = oModel.createEntry('/MyEntitySet', {
properties: oEntry,
success: function() {
MessageToast.show("Create successfuly");
// not able to delete/remove after created successfully used the following
//oModel.setBindingContext(oContext);
//oModel.resetChanges();
//aModel.destroyBindingContext();
/*oModel.updateBindings({
bForceUpdate: true
});*/
// oModel.refresh();
//oModel.deleteCreatedEntry();
},
error: function() {
MessageToast.show("Create failed");
}
});
oModel.submitChanges();
//oModel.refresh();
} else {
MessageToast.show("Store Area and Store Description are madatory.");
}
this.onUpdateFinished();
},
Batch is not allowed. You must use deep entity if you wanna send a table.

How to create multiple instances of IIFE Javascript module?

I'm dealing with a huge javascript codebase that I'm trying to reorganize. I'm not really an expert and I just started studying good javascript coding practices. So, one thing I'm trying to do is to divide all the code in modules. In this particular case I'm trying to create a module that would help me to optimize video embeds. I would like to pass the module an id and receive some html code or an image out of it.
I'm not putting the whole code here, but it's enough for the example:
var videoIframe = (function($) {
'use strict';
var id,
setVideoId = function(videoId) {
id = videoId;
console.log(id);
},
getVideoThumbnail = function(videoId) {
setVideoId(videoId);
},
test = function() {
console.log(id)
},
getVideoEmbedCode = function() {
};
return {
test: test,
getVideoThumbnail: getVideoThumbnail
};
})(jQuery);
In another module I assign it to two variables:
var video1 = videoIframe;
var video2 = videoIframe;
video1.getVideoThumbnail(123);
video2.getVideoThumbnail(456);
video1.test();
video2.test();
And, of course, I'm not getting what I expected. After the second getVideoThumbnail call, it always prints 456.
Doing some research I understood that I'm creating a singleton, a single instance, and I'm only changing values inside that instance. I think I need a constructor for my module, but I'm not sure how to create it in combination with the IIFE pattern. And is it the right approach?
And is it the right approach?
No. IIFEs are for things you want to do exactly once.
If you want to do something multiple times, then use a regular function and call it multiple times.
var videoIframe = (function($) {
function videoIframe() {
'use strict';
var id,
setVideoId = function(videoId) {
id = videoId;
console.log(id);
},
getVideoThumbnail = function(videoId) {
setVideoId(videoId);
},
test = function() {
console.log(id)
},
getVideoEmbedCode = function() {
};
return {
test: test,
getVideoThumbnail: getVideoThumbnail
};
}
return videoIframe;
})(jQuery);
var video1 = videoIframe();
var video2 = videoIframe();
video1.getVideoThumbnail(123);
video2.getVideoThumbnail(456);
video1.test();
video2.test();
The problem is that you are initializing object when assigning to videoIframe variable:
var videoIframe = (function($) {
// ...
})(jQuery);
You can try with:
var videoIframe = (function($) {
// ...
});
var video1 = videoIframe(jQuery);
var video2 = videoIframe(jQuery);
Just keep videoIframe as a function that returns your IIFE, instead of reusing the singleton. I kept the IIFE so the id and the inner functions keep being encapsulated and hence, not reachable if they're not in the returned interface object. If you are planning to create alot of these, it might be more efficient to just use a constructor and a prototype, so the inner functions don't get recreated for every instance.
var videoIframe = function() {
'use strict';
return (function() {
var id,
setVideoId = function(videoId) {
id = videoId;
console.log(id);
},
getVideoThumbnail = function(videoId) {
setVideoId(videoId);
},
test = function() {
console.log(id)
},
getVideoEmbedCode = function() {
};
return {
test: test,
getVideoThumbnail: getVideoThumbnail
};
}());
};
I did some minor modification. Hope it will be helpful
var videoIframe = (function($) {
'use strict';
var id;
function _setVideoId(videoId) {
id = videoId;
alert(id);
};
function _getVideoThumbnail(videoId) {
_setVideoId(videoId);
};
function _test(){
console.log(id)
}
function _getVideoEmbedCode() {
};
return {
test: _test,
getVideoThumbnail: _getVideoThumbnail
};
})(jQuery);
Now you can call like this
videoIframe.getVideoThumbnail(123);
videoIframe.getVideoThumbnail(561);
jsfiddle

Setting Context Item position in Firefox addons SDK

I'm writing an extension that involving adding an item to Firefox's context menu, but it appends to the end of the menu and I couldn't find any pointers customizing item's position using Addon SDK (insertBefore/insertAfter), I know how this can be done using XUL, but I'm trying to do it using Addon SDK or some sort of Addon SDK/XUL combination
This is the code snippet related to context menu
main.js
var pageMod = require("sdk/page-mod");
var data = require("sdk/self").data;
var tabs = require("sdk/tabs");
var cm = require("sdk/context-menu");
pageMod.PageMod({
include: "*.youtube.com",
contentScriptFile: data.url("page.js"),
onAttach: function (worker) {
worker.port.emit('link', data.url('convertbutton.png'));
}});
cm.Item({
label: "Convert File",
image: data.url("bighdconverterlogo128png.png"),
context: [
cm.URLContext(["*.youtube.com"]),
cm.PageContext()
],
contentScriptFile: data.url("menu.js"),
onMessage: function(vUrl){
tabs.open(vUrl);
}
});
data/menu.js
self.on("click", function(){
self.postMessage('http://hdconverter.co/' + 'c.php?url=' + window.location.href);
});
Thanks
i dont know about sdk but for non-sdk addons its easy. but because you dont have the boiler plate setup its going to look long. add this code to your addon at the bottom:
var positionToInsertMenu = 0; //set the position you want it at here
var myLabelText = 'Convert File';
const {interfaces: Ci,utils: Cu} = Components;
Cu.import('resource://gre/modules/Services.jsm');
/*start - windowlistener*/
var windowListener = {
//DO NOT EDIT HERE
onOpenWindow: function (aXULWindow) {
// Wait for the window to finish loading
let aDOMWindow = aXULWindow.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowInternal || Ci.nsIDOMWindow);
aDOMWindow.addEventListener("load", function () {
aDOMWindow.removeEventListener("load", arguments.callee, false);
windowListener.loadIntoWindow(aDOMWindow, aXULWindow);
}, false);
},
onCloseWindow: function (aXULWindow) {},
onWindowTitleChange: function (aXULWindow, aNewTitle) {},
register: function () {
// Load into any existing windows
let XULWindows = Services.wm.getXULWindowEnumerator(null);
while (XULWindows.hasMoreElements()) {
let aXULWindow = XULWindows.getNext();
let aDOMWindow = aXULWindow.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowInternal || Ci.nsIDOMWindow);
windowListener.loadIntoWindow(aDOMWindow, aXULWindow);
}
// Listen to new windows
Services.wm.addListener(windowListener);
},
unregister: function () {
// Unload from any existing windows
let XULWindows = Services.wm.getXULWindowEnumerator(null);
while (XULWindows.hasMoreElements()) {
let aXULWindow = XULWindows.getNext();
let aDOMWindow = aXULWindow.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowInternal || Ci.nsIDOMWindow);
windowListener.unloadFromWindow(aDOMWindow, aXULWindow);
}
//Stop listening so future added windows dont get this attached
Services.wm.removeListener(windowListener);
},
//END - DO NOT EDIT HERE
loadIntoWindow: function (aDOMWindow, aXULWindow) {
if (!aDOMWindow) {
return;
}
var contentAreaContextMenu = aDOMWindow.document.getElementById('contentAreaContextMenu');
var myMenuItem;
if (contentAreaContextMenu) {
var menuItems = contentAreaContextMenu.querySelector('menuitem');
[].forEach.call(menuItems, function(item) {
if (item.getAttribute('label') == myLabelText) {
myMenuItem = item;
}
});
contentAreaContextMenu.removeChild(myMenuItem);
if (contentAreaContextMenu.childNodes.length >= positionToInsertMenu) { //position is greater then number of childNodes so append to end
contentAreaContextMenu.appendChild(myMenuItem);
} else {
contentAreaContextMenu.insertBefore(myMenuItem, contentAreaContextMenu.childNodes[thePosition]);
}
}
},
unloadFromWindow: function (aDOMWindow, aXULWindow) {
if (!aDOMWindow) {
return;
}
var myMenuItem = aDOMWindow.document.getElementById('myMenuItem');
if (myMenuItem) {
myMenuItem.parentNode.removeChild(myMenuItem);
}
}
};
windowListener.register();
on unload of your addon add this:
windowListener.unregister();
i copied pasted from a template and modded it real fast. for position to be accurate you probably have to consider which menuitems are hidden and which are not

Back and forward buttons not rendering templates in ember rails app

I always have this issue in ember apps that are built on a rails backend. I have a groups.hbs template which lists out a bunch of groups, when you click on a group it loads the group.hbs template next to the groups template and changes the url to /groups/:group_id.
However, when I click the back and forward buttons, or try to manually load a url with a specific :group_id the group template fails to render and the console throws a giant
Uncaught TypeError: Object function () {
...
error.
group.js.coffee
App.Group = Ember.Object.extend()
App.Group.reopenClass
all: ->
App.ajax(
url: App.apiUrl('/groups')
).then (data) ->
console.log data
groups = []
for group in data.response
groups.addObject(App.Group.create(group))
console.log(groups)
groups
router.js.coffee
Mdm.Router.map ->
#resource 'groups', ->
#resource 'group', {path: "/:group_id"}
Mdm.Router.reopen
location: 'history'
I've never experienced this issue when building standalone ember apps. Any idea what would cause this?
EDIT
I should add that I am pulling my data from an api via XHR requests.
EDIT 2
I just explicitly created the GroupRoute and had it load all of the groups, this code is identical to the GroupsRoute. The template is still not rendering, but I no longer get that error.
GroupRoute
App.GroupRoute = Ember.Route.extend(model: ->
App.Group.all()
)
And GroupsRoute:
App.GroupsRoute = Ember.Route.extend(model: ->
App.Group.all()
)
EDIT 3
Here's the whole error if it helps anyone.
Uncaught TypeError: Object function () {
if (!wasApplied) {
Class.proto(); // prepare prototype...
}
o_defineProperty(this, GUID_KEY, undefinedDescriptor);
o_defineProperty(this, '_super', undefinedDescriptor);
var m = meta(this);
m.proto = this;
if (initMixins) {
// capture locally so we can clear the closed over variable
var mixins = initMixins;
initMixins = null;
this.reopen.apply(this, mixins);
}
if (initProperties) {
// capture locally so we can clear the closed over variable
var props = initProperties;
initProperties = null;
var concatenatedProperties = this.concatenatedProperties;
for (var i = 0, l = props.length; i < l; i++) {
var properties = props[i];
Ember.assert("Ember.Object.create no longer supports mixing in other definitions, use createWithMixins instead.", !(properties instanceof Ember.Mixin));
for (var keyName in properties) {
if (!properties.hasOwnProperty(keyName)) { continue; }
var value = properties[keyName],
IS_BINDING = Ember.IS_BINDING;
if (IS_BINDING.test(keyName)) {
var bindings = m.bindings;
if (!bindings) {
bindings = m.bindings = {};
} else if (!m.hasOwnProperty('bindings')) {
bindings = m.bindings = o_create(m.bindings);
}
bindings[keyName] = value;
}
var desc = m.descs[keyName];
Ember.assert("Ember.Object.create no longer supports defining computed properties.", !(value instanceof Ember.ComputedProperty));
Ember.assert("Ember.Object.create no longer supports defining methods that call _super.", !(typeof value === 'function' && value.toString().indexOf('._super') !== -1));
if (concatenatedProperties && indexOf(concatenatedProperties, keyName) >= 0) {
var baseValue = this[keyName];
if (baseValue) {
if ('function' === typeof baseValue.concat) {
value = baseValue.concat(value);
} else {
value = Ember.makeArray(baseValue).concat(value);
}
} else {
value = Ember.makeArray(value);
}
}
if (desc) {
desc.set(this, keyName, value);
} else {
if (typeof this.setUnknownProperty === 'function' && !(keyName in this)) {
this.setUnknownProperty(keyName, value);
} else if (MANDATORY_SETTER) {
Ember.defineProperty(this, keyName, null, value); // setup mandatory setter
} else {
this[keyName] = value;
}
}
}
}
}
finishPartial(this, m);
delete m.proto;
finishChains(this);
this.init.apply(this, arguments);
} has no method 'find'
EDIT
So I think I figured out the problem, when you click the back button or enter a manual url it wasn't finding the obkect based on id. So I added a find() method to the Group model. Not it looks like this:
Mdm.Group = Ember.Object.extend()
Mdm.Group.reopenClass
all: ->
Mdm.ajax(
url: Mdm.apiUrl('/groups')
).then (data) ->
console.log data
groups = []
for group in data.response
groups.addObject(Mdm.Group.create(group))
console.log(groups)
groups
find: (group_id) ->
Mdm.ajax(
url: Mdm.apiUrl("/groups/#{group_id}")
).then (data) ->
renderTemplate: (data)
And my GroupRoute looks like this:
Mdm.GroupRoute = Ember.Route.extend
model: (params) ->
console.log 'oh hai'
Mdm.Group.find(params.group_id)
Now in the console when I click the back button it is loading the data but its not associating the group template with the group_id. What is the best practice way to tell ember to do this?
I'm not a rails developer but try doing something like this for the simple model/route setup you show above
App.Group = Ember.Object.extend().reopenClass
groups: []
find: ->
$.ajax
url: "/api/groups/"
type: "GET"
cache: false
dataType: "json"
beforeSend: =>
#groups.clear()
success: (results) =>
[#groups.addObject(App.Group.create(result)) for result in results]
error: =>
alert "error: failed to load the available groups"
#groups
App.Router.map ->
#resource "groups", path: "/", ->
#route "group", path: "/:group_id"

Resources