Loading itemTemplate for WinJS.UI.ListView from external source - winjs

I am wondering if someone can shed some light on why this does not work.
I can successfully dynamically template each WinJS.UI.ListView item if I define the templates in my html view (First Scenario). However if I load the template from a seperate html file using a $.get statement it does not work (Second Scenario).
self.selectTemplate = function (itemPromise) {
return itemPromise.then(function (item) { ...
First Scenario:
(var itemTemplate = document.getElementById(item.data.controlType + "ItemTemplate");
var container = document.createElement("div");
itemTemplate.winControl.render(item.data, container);
return container;)
Second Scenario:
(var itemTemplatePromise = ko.bindingHandlers.searchPropertyBuilder.loadTemplate(item.data.controlType);
itemTemplatePromise.done(function (itemTemplateLoaded) {
var templateContainer = document.createElement("div");
templateContainer.innerHTML = itemTemplateLoaded;
templateElement = templateContainer.firstChild;
WinJS.UI.process(templateElement);
var container = document.createElement("div");
templateElement.winControl.render(item.data, container);
return container;
});)
}
WinJS.Utilities.markSupportedForProcessing(self.selectTemplate);
WinJS.Namespace.define("TemplateSelector", {
template: self.selectTemplate
});

I can see one bug in the code. but not sure if that is the only issue here. promises needs to be chained. winjs.ui.processAll returns a promise.
itemTemplatePromise.then(function (itemTemplateLoaded) {
var templateContainer = document.createElement("div");
templateContainer.innerHTML = itemTemplateLoaded;
templateElement = templateContainer.firstChild;
return WinJS.UI.processAll(templateElement);
}).then(function onprocessall()
{
var container = document.createElement("div");
templateElement.winControl.render(item.data, container);
return container;
});

Related

Number of items to show in Javascript

I'm using Content Search Web Part on SP 2013, I'm trying to get the value for Number of items to show option in Javascript from the ctx object. I have tried ctx.ListData.ResultTables[0].RowCount but seems like this value is for the count on the current page only, not the configured in the 'Number of items to show' option within web part configuration.
Number of items to show value in UI
In addition, do you know where can I find more information on how to debug the ctx object or the properties or methods it uses. Any help would be appreciated. Thanks in advance.
We can use JSOM to achieve it. The following code for your reference.
<script type="text/javascript">
ExecuteOrDelayUntilScriptLoaded(retrieveWPProperties, "sp.js");
function retrieveWPProperties(){
var pageurl=_spPageContextInfo.serverRequestPath; //current page
var currentCtx = new SP.ClientContext.get_current();
var pageFile = currentCtx.get_web().getFileByServerRelativeUrl(pageurl);
var webPartManager = pageFile.getLimitedWebPartManager(SP.WebParts.PersonalizationScope.shared);
var webPartDefs = webPartManager.get_webParts();
currentCtx.load(webPartDefs, 'Include(WebPart.Properties)');
currentCtx.executeQueryAsync(
function () {
if (webPartDefs.get_count()) {
for (var i = 0; i < webPartDefs.get_count() ; i++) {
var webPartDef = webPartDefs.getItemAtIndex(i);
var webPart = webPartDef.get_webPart();
var properties = webPart.get_properties();
//console.log(JSON.stringify(properties.get_fieldValues())); //print all properties
if(properties.get_fieldValues().Title=="Content Search"){
var resultsPerPage=properties.get_fieldValues().ResultsPerPage;
alert(resultsPerPage);
}
}
}
else {
console.log("No web parts found.");
}
},
function (sender, args) {
console.log(args.get_message());
});
}
</script>

FabricJS double click on objects

I am trying to perform a special action whenever the user double clicks any object located inside the canvas. I have read the docs and not found any mouse:dblclick-like event in the documentation. I tried doing something like:
fabric.util.addListener(fabric.document, 'dblclick', callback);
Which does trigger the dblclick event but does not give specific information about the actual object that is being clicked on the canvas.
Any ideas of the most FabricJS-y way of doing this?
The more elegant way is to override fabric.Canvas._initEventListeners to add the dblclick support
_initEventListeners: function() {
var self = this;
self.callSuper('_initEventListeners');
addListener(self.upperCanvasEl, 'dblclick', self._onDoubleClick);
}
_onDoubleClick: function(e) {
var self = this;
var target = self.findTarget(e);
self.fire('mouse:dblclick', {
target: target,
e: e
});
if (target && !self.isDrawingMode) {
// To unify the behavior, the object's double click event does not fire on drawing mode.
target.fire('object:dblclick', {
e: e
});
}
}
I've also developed a library to implement more events missed in fabricjs : https://github.com/mazong1123/fabric.ext
This is similar to #LeoCreer's answer but actually gets access to the targeted object
fabric.util.addListener(canvas.upperCanvasEl, 'dblclick', function (e) {
var target = canvas.findTarget(e);
});
The Correct way to add custom events to Fabric.js
window.fabric.util.addListener(canvas.upperCanvasEl, 'dblclick', function (event, self) {
yourFunction(event);
});
or use fabric.ext
I'm using this workaround:
var timer = 0;
canvas.item(0).on('mouseup', function() {
var d = new Date();
timer = d.getTime();
});
canvas.item(0).on('mousedown', function() {
var d = new Date();
if ((d.getTime() - timer) < 300) {
console.log('double click')
}
});
Here is a quick and easy way to add a double click event handler to Fabric JS -
Include following code snippet to your html file. Just ensure this is loaded after the main fabric.js library
<script type="text/javascript">
fabric = (function(f) { var nativeOn = f.on; var dblClickSubscribers = []; var nativeCanvas = f.Canvas; f.Canvas = (function(domId, options) { var canvasDomElement = document.getElementById(domId); var c = new nativeCanvas(domId, options); c.dblclick = function(handler) { dblClickSubscribers.push(handler) }; canvasDomElement.nextSibling.ondblclick = function(ev){ for(var i = 0; i < dblClickSubscribers.length; i++) { console.log(ev); dblClickSubscribers[i]({ e :ev }); } }; return c; }); return f; }(fabric));
</script>
Then add this code to listen a double click event:
canvas.dblclick(function(e) {
});
To get information about the actual object that is being clicked on the canvas, use following method -
canvas.getActiveObject();
eg.
canvas.dblclick(function(e) {
activeObject = canvas.getActiveObject();
});
I am late but now fabricjs has mousedblclick event.
Listed at: http://fabricjs.com/docs/fabric.Object.html
See all events:
http://fabricjs.com/events

PublishingRolloutImage not persisting on Update();

I have a list, that has three fields: Title, PublishingRollupImage and Description.
I want to upload the image to the library SiteCollectionImages and reference it on the list.
I'm able to upload the file to the folder SiteCollectionImages, and get it's url.
I'm also able to insert the item in the list "MyList", but the PublishingRolloutImage won't persist after the Update() method. I already tried to set the constructor for the ImageFieldValue, like this:
new ImageFieldValue("<img src='test.jpg' />");
but it didn't work.
Here's my code:
using (var site = new SPSite(SPContext.Current.Site.ID))
using (var web = site.OpenWeb())
{
var folder = web.GetFolder("SiteCollectionImages");
var file = folder.Files.Add(fileName, file, true);
folder.Update();
var list = web.Lists["MyList"];
var item = list.Items.Add();
item["Title"] = "MyItemTitle";
item["PublishingRollupImage"] = new ImageFieldValue { ImageUrl = file.Url };
item["Description"] = "MyDescription";
item.Update();
}
What i'm doing wrong?
After a lot of trial and error, i found out that i was doing two things wrong:
this:
item["PublishingRollupImage"] = new ImageFieldValue { ImageUrl = file.Url };
was supposed to be like this:
var image = item["PublishingRollupImage"] as ImageFieldValue ?? new ImageFieldValue();
image.ImageUrl = String.Format("/{0}", file.Url);
item["PublishingRollupImage"] = image;
and file.Url needs to start with a slash. If it doesn't start with a slash, it will break after the Update(); method. That's the reason for the String.Format up there.

Resizing MonoTouch.Dialog StyledMultilineElement after an async call

I'm playing with MonoTouch.Dialog and written some code to show some tweets. The problem is that the table cells are too small and the cells are all bunched up when I load the StyledMultilineElements asynchronously. They look absolutely perfect when I load them synchronously (i.e. without the QueueUserWorkItem/InvokeOnMainThread part)
Is there a way of getting the table cells to recalculate their height?
// This method is invoked when the application has loaded its UI and its ready to run
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
window.AddSubview(navigation.View);
var tweetsSection = new Section("MonoTouch Tweets"){
new StringElement("Loading...") //placeholder
};
var menu = new RootElement("Demos"){
tweetsSection,
};
var dv = new DialogViewController(menu) { Autorotate = true };
navigation.PushViewController(dv, true);
window.MakeKeyAndVisible();
// Load tweets async
UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true;
ThreadPool.QueueUserWorkItem(delegate {
var doc = XDocument.Load("http://search.twitter.com/search.atom?q=%23MonoTouch");
var atom = (XNamespace)"http://www.w3.org/2005/Atom";
var tweets =
from node in doc.Root.Descendants(atom + "entry")
select new {
Author = node.Element(atom + "author").Element(atom + "name").Value,
Text = node.Element(atom + "title").Value
};
var newElements =
from tweet in tweets
select new StyledMultilineElement(
tweet.Author,
tweet.Text);
InvokeOnMainThread(delegate {
UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
tweetsSection.Remove(0);
tweetsSection.Add(newElements.Cast<Element>().ToList());
});
});
return true;
}
Try setting the UnevenRows property on your top level Root element of your Dialog View Controller, in this case "menu":
menu.UnevenRows = true

How to get current Item in Custom Form Action Sharepoint Designer

On custom edit page of list item, I want to do the following
- On clicking Form Action Hyperlink [DataView Control], custom form action will fire to update
a item hidden field [Status].
I already tried the following
- Passing #ID to the work flow but didnt work
- Create a duplicate ID column and updated it with the ID on Item Creation. and then tried to access in "Update Item in" Action but getting "An unexpected error has occurred" while running it.
[Remember i can only use sharepoint designer]
Try to use these javascript functions:
function GetQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
}
function GetCurrentItem() {
var itemId = GetQueryVariable("ID");
try {
var context = new SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle('list-title');
this.currItem = list.getItemById(itemId);
context.load(currItem);
context.executeQueryAsync(Function.createDelegate(this, this.funcSuccess), Function.createDelegate(this, this.funcFailed));
}
catch (e) {
alert(e);
}
}
function funcSuccess() {}
function funcFailed() {}

Resources