How can I hover on a rectangle in Javascript? - javascript

I created a rectangle on the screen and I want some buttons to appear on the rectangle when mouseover it. But I couldn't handle this work. My code is below. I couldn't understand that why
this.$('.control').removeClass('hide');
this row is not working. It does not give any error also.
$(this.rect).html(................
........css({ position: 'absolute', padding: '10px' });
I couldn't understand also that this part of my code. (Stack didn't allow the divs. I don't know why).
var KineticModel = Backbone.Model.extend({
myRect: null,
createRect : function() {
alert("rectangle created.");
var rect=new Kinetic.Rect({
x: 50,
y: 50,
width: 150,
height: 150,
fill: 'green',
stroke: 'black',
strokeWidth: 1,
offset: [0, 0],
draggable: true,
});
rect.on("mouseover",function(){
alert("Hoover : ");
$('.control').removeClass('hide');
});
rect.on("mouseout",function(){
alert("Out : ");
});
rect.on("mousedown",function(){
alert("Down : ");
});
rect.on("mouseup",function(){
alert("Up : ");
});
return rect;
}
});
var KineticView = Backbone.View.extend({
tagName: 'span',
stage: null,
layer: null,
initialize: function (options) {
model: options.model;
el: options.el;
this.layer = new Kinetic.Layer();
this.stage = new Kinetic.Stage({ container: this.el, width: 1000, height: 500 });
this.stage.add(this.layer);
},
events: {
'click': 'spanClicked'
},
render: function () {
var rect = this.model.createRect();
$(this.rect).html('<div class="shape"/>'
+ '<div class="control delete hide"/>'
+ '<div class="control change-color hide"/>'
+ '<div class="control resize hide"/>'
+ '<div class="control rotate hide"/>').css({ position: 'absolute', padding: '10px' });
this.layer.add(rect);
this.stage.add(this.layer);
alert("render");
return this;
},
spanClicked: function () {
}
});
var kModel = new KineticModel({});
var kView = new KineticView({ el: '#container', model: kModel });
$('#shapetest').click(function() {
kView.render();
});

change this.$('.control').removeClass('hide'); to :
$('.control').removeClass('hide');
And so on ...

Related

JointJS: Multiple Templates for different Objects

I am actually working on a tool to visualize data flow. I have different types
of elements which should be used and would like to have for everyone of those elements (objects) a own html template. Does anyone have a idea if this is possible and how to implement this?
Thanks a lot for your help I really appreciate that!
Dear regards,
Raphael
Here my code (sorry for the mess):
(function() {
var graph = new joint.dia.Graph;
var paper = new joint.dia.Paper({ el: $('#paper'), width: 650, height: 400, gridSize: 1, model: graph });
// Create a system element.
// -----------------------------------------------------------------------------
joint.shapes.html = {};
joint.shapes.html.Element = joint.shapes.basic.Generic.extend(_.extend({}, joint.shapes.basic.PortsModelInterface, {
markup: '<g class="rotatable"><g class="scalable"><rect/></g><g class="inPorts"/><g class="outPorts"/></g>',
portMarkup: '<g class="port<%= id %>"><circle/></g>',
defaults: joint.util.deepSupplement({
type: 'html.Element',
size: { width: 100, height: 80 },
inPorts: [],
outPorts: [],
attrs: {
'.': { magnet: false },
rect: {
stroke: 'none', 'fill-opacity': 0, width: 170, height: 250,
},
circle: {
r: 6, //circle radius
magnet: true,
stroke: 'black'
},
'.inPorts circle': { fill: 'green', magnet: 'passive', type: 'input'},
'.outPorts circle': { fill: 'red', type: 'output'}
}
}, joint.shapes.basic.Generic.prototype.defaults),
getPortAttrs: function (portName, index, total, selector, type) {
var attrs = {};
var portClass = 'port' + index;
var portSelector = selector + '>.' + portClass;
var portCircleSelector = portSelector + '>circle';
attrs[portCircleSelector] = { port: { id: portName || _.uniqueId(type), type: type } };
attrs[portSelector] = { ref: 'rect', 'ref-y': (index + 0.5) * (1 / total) };
if (selector === '.outPorts') { attrs[portSelector]['ref-dx'] = 0; }
return attrs;
}
}));
// -------------------------------------------------------------------------------------------------------------------------------------
// Create a custom view for that element that displays an HTML div above it.
// -------------------------------------------------------------------------------------------------------------------------------------
joint.shapes.html.ElementView = joint.dia.ElementView.extend({
objectname: "System",
template: [
'<div class="html-element" id=>',
'<button class="delete">x</button>',
'<button class="add">+</button>',
'<div class="head">',
'<h3>',
'System',
'</h3>',
'<input type="text" class="systemComment" placeholder = "Add a comment to this System"/>',
'</div> </br>',
'</div>'
].join(''),
//::: Start initialize function :::
initialize: function() {
_.bindAll(this, 'updateBox');
joint.dia.ElementView.prototype.initialize.apply(this, arguments);
this.$box = $(_.template(this.template)());
// Prevent paper from handling pointerdown.
this.$box.find('input,select').on('mousedown click', function(evt) {
evt.stopPropagation();
});
// This is an example of reacting on the input change and storing the input data in the cell model.
this.$box.find('input').on('change', _.bind(function(evt) {
this.model.set('input', $(evt.target).val());
}, this));
this.$box.find('select').on('change', _.bind(function(evt) {
this.model.set('select', $(evt.target).val());
}, this));
this.$box.find('select').val(this.model.get('select'));
this.$box.find('.delete').on('click', _.bind(this.model.remove, this.model));
$('.add').on('click', function(){
//we select the box clone it and insert it after the box
$(".html-element").clone().appendTo("#paper");
});
// Update the box position whenever the underlying model changes.
this.model.on('change', this.updateBox, this);
// Remove the box when the model gets removed from the graph.
this.model.on('remove', this.removeBox, this);
this.updateBox();
},
//::: End initialize function :::
//::: Start render function :::
render: function() {
joint.dia.ElementView.prototype.render.apply(this, arguments);
this.paper.$el.prepend(this.$box);
// this.paper.$el.mousemove(this.onMouseMove.bind(this)), this.paper.$el.mouseup(this.onMouseUp.bind(this));
this.updateBox();
return this;
},
//::: End render function :::
//::: Start renderPortst function :::
renderPorts: function () {
var $inPorts = this.$('.inPorts').empty();
var $outPorts = this.$('.outPorts').empty();
var portTemplate = _.template(this.model.portMarkup);
_.each(_.filter(this.model.ports, function (p) { return p.type === 'in' }), function (port, index) {
$inPorts.append(V(portTemplate({ id: index, port: port })).node);
});
_.each(_.filter(this.model.ports, function (p) { return p.type === 'out' }), function (port, index) {
$outPorts.append(V(portTemplate({ id: index, port: port })).node);
});
},
//::: End renderPortst function :::
//::: Start update function
update: function () {
// First render ports so that `attrs` can be applied to those newly created DOM elements
// in `ElementView.prototype.update()`.
this.renderPorts();
joint.dia.ElementView.prototype.update.apply(this, arguments);
},
//::: End update function :::
//::: Start updateBox function
updateBox: function() {
// Set the position and dimension of the box so that it covers the JointJS element.
var bbox = this.model.getBBox();
// Example of updating the HTML with a data stored in the cell model.
// paper.on('blank:pointerdown', function(evt, x, y) { this.$box.find('textarea').toBack(); });
this.model.on('cell:pointerclick', function(evt, x, y) { this.$box.find('textarea').toFront(); });
this.$box.css({ width: bbox.width, height: bbox.height, left: bbox.x + 15, top: bbox.y, transform: 'rotate(' + (this.model.get('angle') || 0) + 'deg)' });
},
//::: End updateBox function :::
//::: Start removeBox function :::
removeBox: function(evt) {
this.$box.remove();
}
//::: End removeBox function :::
});
// -------------------------------------------------------------------------------------------------------------------------------------
// Create JointJS elements and add them to the graph as usual.
// -------------------------------------------------------------------------------------------------------------------------------------
var system = new joint.shapes.html.Element({
position: { x: 80, y: 80 },
size: { width: 240, height: 180 },
outPorts:['systemOut'],
inPorts: ['systemIn'],
});
var dbo = new joint.shapes.html.Element({
position: { x: 120, y: 210 },
size: { width: 240, height: 180 },
outPorts:['dboOut'],
inPorts: ['dboIn'],
})
// -------------------------------------------------------------------------------------------------------------------------------------
//Adding all to the graph
graph.addCells([system, dbo]);
}())
you can put the template definition on the model, then you can instantiate elements with custom templates, like this:
new joint.shapes.html.Element({
template: [
'<div class="my-html-element">',
'<div><input data-attribute="myinput" type="checkbox"/></div>',
'<div><input data-attribute="myinput" type="checkbox"/></div>',
'<div><input data-attribute="myinput" type="checkbox"/></div>',
'</div>'
].join(''),
});
Here is an complete example: https://jsfiddle.net/vtalas/pruz7h9w/
Please note there is a new API for easier manipulation with ports since Joint v1.0 (it's applied in demo above as well).

Uncaught SyntaxError: Unexpected token new

i am playing with backbone and i have an error when i am using the model as array, can any one tell me where i am wrong?
$(function () {
var Rectangle = Backbone.Model.extend({});
var RectangleView = Backbone.View.extend({
.....
});
var models [
new Rectangle({
width: 100,
height: 60,
position: {
x: 300,
y: 150
},
color: '#ff0000'
})
];
_(models).each(function(rmodel) {
$('div#canvas').append(new RectangleView({ model: rmodel}).render().el);
});
})();
it is coming from the array
You missed a =
var models = [
new Rectangle({
width: 100,
height: 60,
position: {
x: 300,
y: 150
},
color: '#ff0000'
})
];

Is it possible to combine kinetic.js and backbone.js?

I want to code an app that simply puts a rectangle on the screen. But I need to combine kinetic.js and backbone.js for this and i am not sure it can be done.
Kinetic code is:
document.getElementById('rect').addEventListener('click', function() {
rect = new Kinetic.Rect({
x: 239,
y: 75,
width: 100,
height: 50,
fill: 'green',
stroke: 'black',
strokeWidth: 4,
offset: [50,25],
draggable: true,
});
And backbone code
$(function() {
var Shape = Backbone.Model.extend({
defaults: { x:50, y:50, width:150, height:150, color:'gray' },
setTopLeft: function(x,y) { this.set({ x:x, y:y }); },
setDim: function(w,h) { this.set({ width:w, height:h }); },
isCircle: function() { return !!this.get('circle'); }
});
*I added .html file these paths
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script type="text/javascript" src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.3.3.min.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.2.2/underscore-min.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.5.3/backbone-min.js"></script>
All i want to place kinetic part instead of default values in backbone. Is it possible?
With your help, we wrote this example of work which puts a rectangle on the screen using both kinetic.js and backbone.js. I wish it would be useful for who is looking for this kind of integrated code.
Thanks a lot for your help!
var KineticModel = Backbone.Model.extend({
myRect: null,
createRect : function() {
alert("rectangle created.");
var rect=new Kinetic.Rect({
x: 10,
y: 10,
width: 100,
height: 50,
fill: 'green',
stroke: 'black',
strokeWidth: 1,
offset: [0, 0],
draggable: true,
});
return rect;
}
});
var KineticView = Backbone.View.extend({
tagName: 'span',
stage: null,
layer: null,
initialize: function (options) {
model: options.model;
el: options.el;
this.layer = new Kinetic.Layer();
this.stage = new Kinetic.Stage({ container: this.el, width: 400, height: 400 });
this.stage.add(this.layer);
},
events: {
'click': 'spanClicked'
},
render: function () {
var rect = this.model.createRect();
this.layer.add(rect);
this.stage.add(this.layer);
alert("render");
},
spanClicked: function () {
}
});
var kModel = new KineticModel({});
var kView = new KineticView({ el: '#container', model: kModel });
$('#shapetest').click(function() {
kView.render();
});
Yes this is definitely possible. I would just create a model that stores the data that you will be using in your shape, use a view to render a span tag with click me, attach an event listener to the span and then output the rectangle when the user clicks.
var ShapeModel = Backbone.Model.extend({});
var rectangle = new ShapeModel({
x: 10,
y: 10,
width: 100,
height: 50,
fill: 'green',
stroke: 'black',
strokeWidth: 4,
offset: [0, 0],
draggable: true,
});
var RectangleView = Backbone.View.extend({
tagName: 'span',
initialize: function (options) {
model: options.model;
el: options.el;
},
events: {
'click': 'spanClicked'
},
render: function () {
this.$el.text('click me');
},
spanClicked: function () {
var stage = new Kinetic.Stage({
container: this.el,
width: 200,
height: 200
});
var layer = new Kinetic.Layer();
var rect = new Kinetic.Rect(this.model.toJSON());
layer.add(rect);
stage.add(layer);
}
});
var rectangleView = new RectangleView({ el: '#shapetest', model: rectangle });
rectangleView.render();
I would upgrade to the latest version of Backbone and Underscore too.
Also, thanks for pointing out Kinetic. Hopefully it has support for drawing on the canvas on a mobile device.

Mootools jquery's blockUI equivalent

I am searching for jquery's plugin blockUI functionality for mootools. Do You know some plugin or simple way to block browser for a given time by mootools ?
Here's some code to get you started. http://jsfiddle.net/5BCPS/
taken it out of my plugin here: https://github.com/DimitarChristoff/Modal/blob/master/Source/js/Modal.js
(function() {
this.Modal = {};
Element.implement({
diffuse: function(position){
return this.setStyles({
position: position || 'absolute',
top: 0,
bottom: 0,
left: 0,
right: 0,
height: '100%',
width: '100%'
});
}
});
Modal.Overlay = new Class({
Implements: [Events, Options],
options: {
zIndex: 900000,
opacity: .3,
backgroundColor: '#555',
fx: {
duration: 300
}
},
initialize: function(container, options){
this.setOptions(options);
this.container = document.id(container);
var self = this;
this.element = new Element('div', {
'class': 'overlay',
styles: {
display: 'none',
opacity: 0,
zIndex: this.options.zIndex,
backgroundColor: this.options.backgroundColor
},
events: {
click: function() {
self.fireEvent("overlayClick");
}
},
tween: this.options.fx
}).diffuse('fixed').inject(this.container);
return this;
},
show: function(){
this.element.setStyle("display", "block").fade(this.options.opacity);
return this.fireEvent("show");
},
hide: function(){
this.element.fade(this.options.opacity).get("tween").chain(function() {
this.element.setStyle("display", "none");
});
return this.fireEvent("hide");
}
});
})();
var modal = new Modal.Overlay(document.body, {
hideAfter: 5,
onHide: function() {
// do something.
}
}).show();
modal.hide.delay(3000, modal);
all you need is what you display on top / counter. thats just plain js.

Titanium mobile Javascript objects

Ok so I'm new to Titanium and I'm pretty much a noob at Javascript
I tried doing this:
app.view.newMatrix = function() {
return {
matrix = Titanium.UI.createWindow({
title:'Add a New Matrix',
backgroundColor:'stripped',
navBarHidden: false
}),
// navbar buttons
cancel = Titanium.UI.createButton({
title:'Cancel'
}),
save = Titanium.UI.createButton({
title:'Save',
style:Titanium.UI.iPhone.SystemButton.SAVE
}),
name_label = Titanium.UI.createLabel({
text: "Matrix Name:",
font: { fontsize: 12, fontstyle: 'italic', color: '#336699' },
height: 35,
top: 35,
left: 30,
width: 150,
color: "black"
}),
name = Titanium.UI.createTextArea({
color: '#336699',
height: this.name_label.height,
top: this.name_label.top + 35,
left: this.name_label.left - 10,
width: 275,
borderRadius:15
}),
setItems = function() {
this.win.add(this.name);
this.win.add(this.name_label);
this.win.add(this.desc);
this.win.add(this.desc_label);
Ti.API.info("label:"+ this.name_label.height);
return this.win.open({modal: true, animation: true});
}
}
}
then called it like this:
app.controller.home = function() {
var home = app.view.home();
home.setItems();
home.butn.addEventListener("click", function(e){
app.controller.newMatrix();
});
home.butn2.addEventListener("click", function (e) {
matrix_table(tab);
});
home.butn3.addEventListener("click", function(e){
newItem();
});
home.butn5.addEventListener("click", function (e) {
item_table();
});
}
I did this because I saw a Titanium MVC suggestion here but I don't get why it returns an anonymous object. I can't access properties like name_label from within the name object.
I figured out that I should do this instead:
app.view.newMatrix = function() {
this.matrix = Titanium.UI.createWindow({
title:'Add a New Matrix',
backgroundColor:'stripped',
navBarHidden: false
}),
// navbar buttons
this.cancel = Titanium.UI.createButton({
title:'Cancel'
}),
this.save = Titanium.UI.createButton({
title:'Save',
style:Titanium.UI.iPhone.SystemButton.SAVE
}),
this.name_label = Titanium.UI.createLabel({
text: "Matrix Name:",
font: { fontsize: 12, fontstyle: 'italic', color: '#336699' },
height: 35,
top: 35,
left: 30,
width: 150,
color: "black"
}),
this.name = Titanium.UI.createTextArea({
color: '#336699',
height: this.name_label.height,
top: this.name_label.top + 35,
left: this.name_label.left - 10,
width: 275,
borderRadius:15
}),
this.setItems = function() {
this.win.add(this.name);
this.win.add(this.name_label);
this.win.add(this.desc);
this.win.add(this.desc_label);
Ti.API.info("label:"+ this.name_label.height);
return this.win.open({modal: true, animation: true});
}
}
and call it like this:
app.controller.home = function() {
return {
getView: function() {
var home = app.view.home();
home.setItems();
home.butn.addEventListener("click", function(e){
app.controller.newMatrix();
});
home.butn2.addEventListener("click", function (e) {
matrix_table(tab);
});
home.butn3.addEventListener("click", function(e){
newItem();
});
home.butn5.addEventListener("click", function (e) {
item_table();
});
}
}
}
But I don't know why the first example doesn't work. I mean aren't properties the same as variables? Also I do know that the second example is an object too.. is that how I'm supposed to do them? Also with the second example is the new keyword optional? Should I use it? I kinda wanted to stay away from that cause I'm not sure when I should use it.
thanks I hope I made sense. I do have it working but I don't know if the second example is the right way to go....

Categories

Resources