addTools is giving exception in rappidjs - jointjs

In context of one of my assignment I was trying to use RappidJS. I was trying the below code for connecting an element by dropping it over another element.
https://resources.jointjs.com/tutorial/connecting-by-dropping
But I am getting exception as below
rappid.min.js:14 Uncaught TypeError: Cannot read property 'start' of null
at child.update (rappid.min.js:14)
at child.onRender (rappid.min.js:14)
at child.e.render (rappid.min.js:14)
at child.configure (rappid.min.js:14)
at child.addTools (rappid.min.js:14)
at child.element:pointerup (diagram.js:106)
at triggerEvents (backbone.js:338)
at triggerApi (backbone.js:322)
at eventsApi (backbone.js:110)
at child.Events.trigger (backbone.js:312)
I also took reference from below link
https://resources.jointjs.com/tutorial/link-tools .
Can any one suggest me what wrong I am doing here.
My code snippet is as below
function attachLinks(paper) {
paper.on({
'element:pointerdown': function (elementView, event) {
event.data = elementView.model.position();
},
'element:pointerup': function (elementView, event, x, y) {
var coordinates = new joint.g.Point(x, y);
var elementAbove = elementView.model;
var elementBelow = this.model.findModelsFromPoint(coordinates).find(function (el) {
return (el.id !== elementAbove.id);
});
// If the two elements are connected already, don't
// connect them again (this is application-specific though).
if (elementBelow && self.graph.getNeighbors(elementBelow).indexOf(elementAbove) === -1) {
// Move the element to the position before dragging.
elementAbove.position(event.data.x, event.data.y);
// Create a connection between elements.
var link = new joint.shapes.standard.Link();
link.source(elementAbove);
link.target(elementBelow);
link.addTo(this.model);
// Add remove button to the link.
var removeLinkTool = new joint.linkTools.Remove();
var tools = new joint.dia.ToolsView({
tools: [ removeLinkTool]
});
var linkView = link.findView(this);
linkView.addTools(tools); // getting exception at this place.
}
}
});
}

This issue is reproducible only in the paper async mode.
Make sure the view for the link is rendered when you add the link tools. For this please use joint.dia.Paper.prototype.requireView().
// It is fine to use the method in the `sync` mode as the view is rendered/updated
// synchronously as soon as the link is added to the graph.
var linkView = link.findView(paper);
// This method makes sure the view is ready to use in the `async` mode.
// It forces the view to render/update synchronously.
var linkView = paper.requireView(link);
Alternatively, you could pass async = false flag when adding the link to the graph to tell the paper to render the particular view synchronously.
link.addTo(graph, { 'async': false });

Related

Phaser 3 can't get the start method to work right

I'm trying to make a menu where the scene changes when the player clicks a button using the start method. At first, I had it all in the create function with this:
var levelOne = this.add.sprite(200, 400, 'LevelOne').setInteractive();
levelOne.on('pointerdown', function (pointer) {
this.scene.start('play');
});
But this led to an error in which it said that this.scene.start isn't a function.
I looked at a previous example where the method worked, the big difference was that the method was in the update function, so I rewrote my code to have this in the create function:
this.choice = 0;
var levelOne = this.add.sprite(200, 400, 'LevelOne').setInteractive();
levelOne.on('pointerdown', function (pointer) {
this.choice = 1;
//game.settings = {
//gameTimer: 60000
//}
});
And this in the update function:
if (this.choice == 1){
this.scene.start('play');
}
Sadly, this didn't work either and didn't even give an error message. I can't tell what went wrong. Please help.
You have to pass the scene as the context to the event function on(...) (link to the documentation), as the third parameter, so that you can access the scene properties and functions in the event callback.
levelOne.on('pointerdown', function (pointer) {
this.scene.start('play');
}, this); // <-- you have to add "this"

Subclassing, extending or wrapping Node.js 'request' module to enhance response

I'm trying to extend request in order to hijack and enhance its response and other 'body' params. In the end, I want to add some convenience methods for my API:
var myRequest = require('./myRequest');
myRequest.get(function(err, hijackedResponse, rows) {
console.log(hijackedResponse.metadata)
console.log(rows)
console.log(rows.first)
});
According to the Node docs on inherits, I thought I could make it work (and using the EventEmitter example in the docs works OK). I tried getting it to work using #Trott's suggestion but realized that for my use case it's probably not going to work:
// myRequest.js
var inherits = require('util').inherits;
var Request = require("request").Request;
function MyRequest(options) {
Request.call(this, options);
}
inherits(MyRequest, Request);
MyRequest.prototype.pet = function() {
console.log('purr')
}
module.exports = MyRequest;
I've been toying with extend as well, hoping that I could find a way to intercept request's onRequestResponse prototype method, but I'm drawing blanks:
var extend = require('extend'),
request = require("request")
function myResponse() {}
extend(myResponse, request)
// maybe some magic happens here?
module.exports = myResponse
Ended up with:
var extend = require('extend'),
Ok = require('objectkit').Ok
function MyResponse(response) {
var rows = Ok(response.body).getIfExists('rows');
extend(response, {
metadata: extend({}, response.body),
rows: rows
});
response.first = (function() {
return rows[0]
})();
response.last = (function() {
return rows[rows.length - 1] || rows[0]
})();
delete response.metadata.rows
return response;
}
module.exports = MyResponse
Keep in mind in this example, I cheated and wrote it all inside the .get() method. In my final wrapper module, I'm actually taking method as a parameter.
UPDATED to answer the edited question:
Here's a rough template for the contents of your myResponse.js. It only implements get(). But as a bare bones, this-is-how-this-sort-of-thing-can-be-done demo, I hope it gets you going.
var request = require('request');
var myRequest = {};
myRequest.get = function (callback) {
// hardcoding url for demo purposes only
// could easily get it as a function argument, config option, whatever...
request.get('http://www.google.com/', function (error, response, body) {
var rows = [];
// only checking error here but you might want to check the response code as well
if (!error) {
// mess with response here to add metadata. For example...
response.metadata = 'I am awesome';
// convert body to rows however you process that. I'm just hardcoding.
// maybe you'll use JSON.parse() or something.
rows = ['a', 'b', 'c'];
// You can add properties to the array if you want.
rows.first = 'I am first! a a a a';
}
// now fire the callback that the user sent you...
callback(error, response, rows);
});
};
module.exports = myRequest;
ORIGINAL answer:
Looking at the source code for the Request constructor, it requires an options object that in turn requires a uri property.
So you need to specify such an object as the second parameter in your call():
Request.call(this, {uri: 'http://localhost/'});
You likely don't want to hard code uri like that inside the constructor. You probably want the code to look something more like this:
function MyRequest(options) {
Request.call(this, options);
}
...
var myRequest = new MyRequest({uri: 'http://localhost/'});
For your code to work, you will also need to move util.inherits() above the declaration for MyRequest.prototype.pat(). It appears that util.inherits() clobbers any existing prototype methods of the first argument.

Deselection fabric.js object event

I am trying to execute some code every time a specific fabric object is "deselected". Is there any deselection event I can handle? I already have a function for when the object is selected, via the selected event, but have not found any documentation about the deselected one. At the canvas level I have the selection:cleared and selection:created events, but nothing for the deselection either.
Cheers,
Gonzalo
Use the before:selection:cleared event and get the active object or group. After that you can check if it corresponds to your specific fabric object.
canvas.on('before:selection:cleared', function() {
var clearedObject;
if(typeof(canvas.getActiveObject()) !== 'undefined') {
clearedObject = canvas.getActiveObject();
}
else {
clearedObject = canvas.getActiveGroup();
}
//do stuff with the deselected element if it is the specific one you want.
});
Just to let you all know that the newest versions of Fabric.js include a deselected event for the Object class. The only thing you need to do now is:
var aFabricObject = <create your fabric object>
aFabricObject.on('deselected', function (options) {
// your code here
});
Update for the upper answer:
The 'deselected' event fires a async method, so you can not get 'options.deselected' immediately.
var aFabricObject = <create your fabric object>
aFabricObject.on('deselected', function (options) {
console.log(options.deselected) // output undefined
setTimeout(() => {
console.log(options.deselected) // output the correct target
}, 0)
});

SP.Ribbon.WebPartComponent.getWebPartAdder() returns undefined

I am using the source at http://blog.symprogress.com/2010/11/ribbon-insert-any-web-part-using-javascript/ to handle user web part button click event.
The function 'addWebPart()' calls a function 'SP.Ribbon.WebPartComponent.getWebPartAdder()' which is supposed to return adder instance but sometimes it returns undefined.
If I add a while loop to wait for the instance value to return correctly, the browser in my VM stalls for some time. When an instance is returned, the browser becomes responsive again. This only happens in some instances.
I am using SharePoint 2013 and the section of code I am referring to is:
addWebPart = function (wpCategory, wpTitle) {
var webPartAdder = SP.Ribbon.WebPartComponent.getWebPartAdder();
while (webPartAdder == undefined)
webPartAdder = SP.Ribbon.WebPartComponent.getWebPartAdder();
// ... Other stuff ...
}
How can this issue be resolved?
For anyone looking for an answer to this question, turns out you have to call 'LoadWPAdderOnDemand()' function then wait for the event '_spEventWebPartAdderReady'. Then query for 'window.WPAdder':
addWebPartDelayed = function (webPartAdder, wpCategory, wpTitle) {
var webPart = findWebPart(webPartAdder, wpCategory, wpTitle);
if (webPart) {
var zone = WPAdder._zones[0];
var wpid = WPAdder._createWebpartPlaceholderInRte();
WPAdder.addItemToPageByItemIdAndZoneId(webPart.id, zone.id, 0, wpid);
}
else
alert('ERROR: Web part not found! Please try again after sometime.');
},
addWebPart = function (wpCategory, wpTitle) {
var webPartAdder = window.WPAdder;
if (webPartAdder == undefined) {
LoadWPAdderOnDemand();
ExecuteOrDelayUntilEventNotified(
function () {
var webPartAdder = window.WPAdder;
addWebPartDelayed(webPartAdder, wpCategory, wpTitle);
},
"_spEventWebPartAdderReady");
}
else
addWebPartDelayed(webPartAdder, wpCategory, wpTitle);
};

Define a global ready function for every page in WinJS

My WinJS app uses the single navigation model. There is some common code that I would like to apply to every page in the app. Instead of placing the code in each page's ready function, I would like to be able to able to define a "global" ready function that will be executed when a page's ready event is fired. Any ideas?
you can define a Mixin object with utility function used for all pages.
utils.js:
PageMixin = {
ready: function ready(element, options)
{
this.element = element;
this.options = options;
this.initialize();
this.onready();
},
initialize: function initialize()
{
// write common initialize code here
}
};
page.js:
var Page = WinJS.UI.Pages.define('/pages/mypage/page.html',
{
onready: function onready()
{
// page specific initialization code here
}
});
// this will make all PageMixin util methods available on Page.
WinJS.Class.mix(Page, PageMixin);
refer WinJS.Class.mixin for details.

Resources